NAME
new_sema - allocate a new semaphore

delete_sema - delete a semaphore

sema_init - initialize a semaphore

sema_post - increment the semaphore's value

sema_wait - decrement the semaphore's value or block

sema_trywait - try to decrement the semaphore's value

SYNOPSIS
#include <mthreads.h>

sem_p new_sema(int n);

void delete_sema(sem_p sp);

sem_p sema_init(sem_p sp, int n);

void sema_post(sem_p sp);

void sema_wait(sem_p sp);

int sema_trywait(sem_p sp);

DESCRIPTION
Semaphores are usually used to control the access to a fixed number of resources. A semaphore is initialized to this number and each thread willing to have access to one of this resources tries to decrement the semaphore's value. If the semapore's value is already zero, the calling thread will be blocked until another thread has incremented the semaphore's value.

new_sema() allocates a new semaphore and initializes its value to n.

delete_sema() deletes a semaphore that has been allocated by new_sema().

sema_init() can be used to initialize an already allocated semaphore. This function is called by new_sema() implicitly. Reinitializing a semaphore that is already in use may cause some threads to get lost!

sema_post() increments the semaphore's value and wakes up one waiting thread if there is any.

sema_wait() tries to decrement the semaphore's value. If this value is already zero, the calling thread will be blocked until another thread increments the value by sema_post(). When the thread is deblocked it tries to decrement the value again. If the value was greater zero, it will get decremented and the call returns immediately.

sema_trywait() tries to decrement the semaphore's value too, but doesn't block the calling thread if the value is already zero. In this case an error is returned. Otherwise, the value will be decremented and the call returns successfully.

RETURN VALUES
Upon successful completion new_sema() returns a valid semaphore handle. Otherwise, a null handle is returned and merrno is set to indicate the error.

sema_trywait returns 1 if has successfully decremented the semaphore's value. Otherwise 0 is returned.

ERRORS
new_sema() will fail if one or more of the following is true: sema_init() will fail it the following is true:
SEE ALSO
mthreads(3), barrier(3), cond(3), mutex(3)