More on Semaphore
POSIX semaphores are available in two flavors: named and unnamed. They differ in how they are created and destroyed, but otherwise work the same. Unnamed semaphores exist in memory only and require that processes have access to the memory to be able to use the semaphores. This means they can be used only by threads in the same process or threads in different processes that have mapped the same memory extent into their address spaces. Named semaphores, in contrast, are accessed by name and can be used by threads in any processes that know their names. In previous lab 6 Synchronization, we introduce the named one(at that time, you do not have the knowledge about multi-threading and memory management) with sem_open()
and sem_close()
functions.
When we want to use POSIX semaphores within a single process, it is easier to use unnamed semaphores. This only changes the way we create and destroy the semaphore. To create an unnamed semaphore, we call the sem_init()
function.
#include <semaphore.h>
int sem_init(sem_t *sem, int pshared, unsigned int value);
The pshared argument indicates if we plan to use the semaphore with multiple processes. If we just want to use the semaphore in a single process, then set it to zero. The value argument specifies the initial value of the semaphore.
Instead of returning a pointer to the semaphore like sem_open()
does, we need to declare a variable of type sem_t
and pass its address to sem_init()
for initialization. After initializing unnamed semaphore using sem_init()
function, the sem_wait()
and sem_post()
functions can operate on the semaphore as lab6 has described.
When we are done using the unnamed semaphore, we can discard it by calling the sem_destroy()
function.
#include <semaphore.h>
int sem_destroy(sem_t *sem);
After calling sem_destroy()
, we can't use any of the semaphore functions with sem unless we reinitialize it by calling sem_init()
again.