Creating and Initializing Semaphores

Syntax

Before a semaphore can be used, it must be declared and initialized. To this end, you need to include the header file synch.h. Then, declare the semaphore you want to use using type sema_t and finally initialize it with function sema_init(). Under Solaris, all semaphore related names started with sema_.

#include  <synch.h>

sema_t   Semaphore;

int  sema_init(
          sema_t  *Semaphore,
          unsigned int   value,
          USYNC_THREAD,
          (void *) NULL);
A call to thr_init() will initialize the given semaphore with the specified value (the second argument).

As a good programming practice, a semaphore should be initialized once at the very beginning of your program and before the threads which use it are created. It is a bad practice to reinitialize semaphores in the middle of program execution.