Semaphore

Library Required

1#include <semaphore.h>

Types

1sem_t       // unique identifier for a semaphore

sem_open()

Opens or creates a named semaphore and returns a pointer to it.

1sem_t *sem_open(const char *name, int oflag, mode_t mode, unsigned int value);

Return Value:

  • Success: Pointer to semaphore
  • Error: SEM_FAILED

Example:

1sem_t *sem = sem_open("/mysem", O_CREAT | O_EXCL, 0644, 2);

sem_close()

Closes a named semaphore descriptor without removing the semaphore.

1int sem_close(sem_t *sem);

Return Value:

  • Success: 0
  • Error: -1

Example:

1sem_close(sem);

sem_unlink()

Removes a named semaphore from the system

1int sem_unlink(const char *name);

Return Value:

  • Success: 0
  • Error: -1

Example:

1sem_unlink("/mysem");

sem_wait()

Decrements (locks) the semaphore, blocking if its value is zero.

1int sem_wait(sem_t *sem);

Return Value:

  • Success: 0
  • Error: -1

Example:

1sem_wait(sem);

sem_trywait()

Tries to decrement the semaphore without blocking; fails if the value is zero.

1int sem_trywait(sem_t *sem);

Return Value:

  • Success: 0
  • Error: -1

Example:

1if (sem_trywait(sem) == -1) {
2    // handle failure without blocking
3}

sem_post()

Increments (unlocks) the semaphore, potentially waking a waiting thread.

1int sem_post(sem_t *sem);

Return Value:

  • Success: 0
  • Error: -1

Example:

1sem_post(sem);

sem_getvalue()

Retrieves the current value of the semaphore.

1int sem_getvalue(sem_t *sem, int *sval);

Return Value:

  • Success: 0
  • Error: -1

Example:

1int val;
2sem_getvalue(sem, &val);

sem_init()

Initializes an unnamed semaphore for use within a process or between processes.

1int sem_init(sem_t *sem, int pshared, unsigned int value);

Return Value:

  • Success: 0
  • Error: -1

Example:

1sem_t sem_local;
2sem_init(&sem_local, 0, 1);

sem_destroy()

Destroys an unnamed semaphore, freeing associated resources.

1int sem_destroy(sem_t *sem);

Return Value:

  • Success: 0
  • Error: -1

Example:

1sem_destroy(&sem_local);
Last updated on