Semaphores

Functions

sem_t * sem_create (int count)
void sem_destroy (sem_t *sem)
void sem_signal (sem_t *sem)
void sem_wait (sem_t *sem)
int sem_wait_tmo (sem_t *sem, tick_t time)

Function Documentation

sem_t* sem_create ( int  count  ) 

Allocates and initialises a semaphore handle. The count argument determines how many times the semaphore can be taken before the calling task is put in the WAITING state.

A counting semaphore being used to guard shared resources should be initialised with the number of available resources. When the semaphore has been taken count times, the task next trying to take the semaphore will be blocked.

A binary semaphore used for synchronisation between two tasks should be initialised to 0. The task trying to take the semaphore will be blocked until the other task calls sem_signal().

A binary semaphore used for mutual exclusion should be initialised to 1. The first task to call sem_wait() will lock the semaphore and other tasks will be blocked until the first task releases it by calling sem_signal(). Note that mutexes are optimised for this type of operation and should normally be used instead of semaphores.

Parameters:
count Number of resources initially available
Returns:
The semaphore handle to be used in all subsequent operations on the semaphore.
void sem_destroy ( sem_t *  sem  ) 

Frees the resources allocated by the semaphore. The semaphore must not be in use when this function is called (no task can be waiting for the semaphore, nor can they do so at any time after calling this function).

Parameters:
sem Semaphore handle
void sem_signal ( sem_t *  sem  ) 

Signals the semaphore. The first task that was waiting on the semaphore (if any) will be put in the READY state.

Parameters:
sem Semaphore handle
void sem_wait ( sem_t *  sem  ) 

Waits for the semaphore. If the semaphore is available, the function will return immediately. If the semaphore is not available, the calling task will be put in the WAITING state until another task calls sem_signal() on the semaphore.

Parameters:
sem Semaphore handle
int sem_wait_tmo ( sem_t *  sem,
tick_t  time 
)

Analogous to sem_wait(), but a maximum time to wait can be specified. If the semaphore is not available, the calling task will wait until the semaphore becomes available, or the number of ticks given by time expires.

Parameters:
sem Semaphore handle
time Number of ticks to wait
Returns:
0 if the semaphore was acquired successfully, 1 if the service timed out.

rt-kernel