Semaphores, Name, Synopsis – Comtrol eCos User Manual
Page 75: Description, Counting

Semaphores
Name
cyg_semaphore_init, cyg_semaphore_destroy, cyg_semaphore_wait,
cyg_semaphore_timed_wait, cyg_semaphore_post, cyg_semaphore_peek
—
Synchronization primitive
Synopsis
#include
<
cyg/kernel/kapi.h
>
void cyg_semaphore_init(cyg_sem_t* sem, cyg_count32 val);
void cyg_semaphore_destroy(cyg_sem_t* sem);
cyg_bool_t cyg_semaphore_wait(cyg_sem_t* sem);
cyg_bool_t cyg_semaphore_timed_wait(cyg_sem_t* sem, cyg_tick_count_t abstime);
cyg_bool_t cyg_semaphore_trywait(cyg_sem_t* sem);
void cyg_semaphore_post(cyg_sem_t* sem);
void cyg_semaphore_peek(cyg_sem_t* sem, cyg_count32* val);
Description
Counting semaphores are a
that allow threads to wait until an event has occurred. The
event may be generated by a producer thread, or by a DSR in response to a hardware interrupt. Associated with
each semaphore is an integer counter that keeps track of the number of events that have not yet been processed. If
this counter is zero, an attempt by a consumer thread to wait on the semaphore will block until some other thread
or a DSR posts a new event to the semaphore. If the counter is greater than zero then an attempt to wait on the
semaphore will consume one event, in other words decrement the counter, and return immediately. Posting to a
semaphore will wake up the first thread that is currently waiting, which will then resume inside the semaphore wait
operation and decrement the counter again.
Another use of semaphores is for certain forms of resource management. The counter would correspond to how
many of a certain type of resource are currently available, with threads waiting on the semaphore to claim a
resource and posting to release the resource again. In practice
are usually much better suited
for operations like this.
cyg_semaphore_init
is used to initialize a semaphore. It takes two arguments, a pointer to a cyg_sem_t structure
and an initial value for the counter. Note that semaphore operations, unlike some other parts of the kernel API, use
pointers to data structures rather than handles. This makes it easier to embed semaphores in a larger data structure.
The initial counter value can be any number, zero, positive or negative, but typically a value of zero is used to
indicate that no events have occurred yet.
cyg_semaphore_wait
is used by a consumer thread to wait for an event. If the current counter is greater than 0,
in other words if the event has already occurred in the past, then the counter will be decremented and the call will
return immediately. Otherwise the current thread will be blocked until there is a
cyg_semaphore_post
call.
75