PREV UP NEXT StackThreads/MP: version 0.77 User's Guide

3.3.2: Semaphore

        int st_sema_init_1(s, c, lim);
@        st_sema_init(s, c);
@        int st_sema_wait(s);
@        int st_sema_trywait(s);
@        int st_sema_post(s);
@        int st_sema_destroy(s);
@               st_sema_t * s; int c, int lim;
@        st_sema_t x = ST_SEMA_INITIALIZER_1(c, p);

Semaphore manages limited resources shared by threads. A semaphore internally maintains a counter. st_sema_init_1(s, c, lim) initializes the counter of s to c. When lim is positive, it specifies the upper limit on the counter. st_sema_init(s) is synonym for st_sema_init_1(s, 0) (no upper limits). st_sema_wait(s) waits the counter of s to become positive and decrements the counter by one. st_sema_trywait(s) behaves like st_sema_wait(s), except it immediately returns value ST_BUSY, when the counter is not positive. st_sema_post(s) increments the counter of s by one. If the upper limit was imposed by st_sema_init(s) and the counter would exceed that value after the increment, an error is signaled. st_sema_destroy(s) destroys s. It signals an error if the counter of s is not the same as the value given at initialization (i.e., st_sema_post were not called as many times as st_sema_wait.). st_sema_t x = ST_SEMA_INITIALIZER_1(c, p) defines a global or static variable x whose counter is c and the upper limit is p.

All these functions return zero upon success and signals an error if an error occurred. Read standard thread books on introduction to semaphore.