How to use POSIX semaphores in C language

C++Server Side ProgrammingProgramming

The semaphore is a concept of process or thread synchronization. Here we will see how to use the semaphores in real programs.

In Linux system, we can get the POSIX semaphore library. To use it, we have to include semaphores.h library. We have to compile the code using the following options.

gcc program_name.c –lpthread -lrt

We can use sem_wait() to lock or wait. And sem_post() to release the lock. The semaphore initializes sem_init() or sem_open() for the Inter-Process Communication (IPC).


#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
sem_t mutex;
void* thread(void* arg) { //function which act like thread
   sem_wait(&mutex); //wait state
   printf("\nEntered into the Critical Section..\n");
   sleep(3); //critical section
   printf("\nCompleted...\n"); //comming out from Critical section
main() {
   sem_init(&mutex, 0, 1);
   pthread_t th1,th2;
   //Join threads with the main thread


soumyadeep@soumyadeep-VirtualBox:~/Cpp_progs$ gcc 1270.posix_semaphore.c -lpthread -lrt
1270.posix_semaphore.c:19:1: warning: return type defaults to ‘int’ [-Wimplicit-int]
main() {
soumyadeep@soumyadeep-VirtualBox:~/Cpp_progs$ ./a.out

Entered into the Critical Section..


Entered into the Critical Section..

Updated on 30-Jul-2019 22:30:26