Semaphores

#include <semaphore.h>

Semaphores are used to synchronize different threads of control. This course does not place an emphasize on the finer points of synchronization, so don't be surprised or dissappointed if you don't understand any of this. If you have questions, feel free to approach a TA on hours.

Semaphores in brickOS are POSIX 1003.b compliant. They must be declared, then initialized, before they can be used.


int sem_init ( sem_t *sem, int pshared, unsigned int value );
Initializes a semaphore, giving it starting value of value.
Parameters: sem - a pointer to the semaphore being initialized
pshared not used by LegOS, usually set to indicate whether the semaphore is shared between processes or not. Just leave it at 0
value The initial value that you want to give the semaphore
returns: 0

int sem_wait ( sem_t *sem );
suspends the calling thread until the semaphore pointed to by sem has non-zero count. It then atomically decreases the semaphore count.
returns: 0

int sem_trywait ( sem_t *sem );
sem_trywait is a non-blocking variant of sem_wait. If the semaphore pointed to by sem has non-zero count, the count is atomically decreased and sem_trywait immediately returns 0. If the semaphore count is zero, sem_trywait immediately returns with error EAGAIN.
returns: a non-zero value if sem was successfully decremented, 0 otherwise

int sem_post ( sem_t *sem );
atomically increases the count of the semaphore pointed to by sem. This function never blocks and can safely be used in asynchronous signal handlers.
Parameters: sem - the semaphore to post

returns: 0

int sem_getvalue ( sem_t *sem, int *sval );
get the semaphore value
Parameters: sem - the semaphore
sval the integer to store the value of the semaphore into

returns: 0

int sem_destroy ( sem_t *sem );
destroys a semaphore object, freeing the resources it might hold. No threads should be waiting on the semaphore at the time sem_destroy is called.
Parameters: sem - the semaphore

returns: 0