Professional Documents
Culture Documents
Orca Share Media1671390184057 7010318534552477988
Orca Share Media1671390184057 7010318534552477988
It initializes a semaphore object pointed by sem, sets its sharing option, and gives it an initial integer value.
The pshared parameter controls the type of semaphore. If the value of pshared is 0, the semaphore is local to the
current process, i.e. private to a single process. Otherwise, the semaphore may be shared between processes. The
third parameter is the value with which to initialize the semaphore. A semaphore created by a call to sem_init() is
destroyed with a call to sem_destoy().
#include <semaphore.h>
int main()
sem_t mySemaphore;
//...
sem_destroy(&mySemaphore;);
return 0;
In the code, we initialized a semaphore with a count of 5. The second parameter of the call to sem_init() is 0, and
this makes the semaphore private to the thread. Passing the value of one would enable the semaphore to be
shared between multiple processes.
2. int sem_post(sem_t *sem); This function atomically increases the value of the semaphore by 1.
3. int sem_try_wait(sem_t *sem); This function will return immediately either having decremented the semap
hore or if the semaphore is already zero.
4. int sem_wait(sem_t *sem); This function atomically decreases the value of the semaphore by 1, but alway
s waits until the semaphore has a nonzero count first. So, if we call sem_wait on a semaphore with a value of 2, the
thread will continue executing but the semaphore will be decreased to 1. If we call it on a semaphore with a value o
f 0, the function will wait until some other thread has incremented the value so that it is no longer 0. If two thread are
both waiting in sem_wait for the same semaphore to be nonzero and it is incremented once by a third process, onl
y one of the two waiting process will get to decrement the semaphore and continue while the other will remain waitin
g.
Practical example using semaphores
Code –
// C program to demonstrate working of Semaphores
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <semaphore.h>
#define THREAD_NUM 16
sem_t semaphore;