How to use POSIX semaphores in C language



The POSIX stands for Portable Operating System which was developed by IEEE (Institute of Electrical and Electronics Engineers). This is UNIX based operating system that is used for both system calls and library functions. The semaphores are used in the process of multithreading and synchronization. For eg. file sharing and memory management. It can be named or unnamed.

Multithreading is the process of executing multiple tasks in the same instance of time while synchronization is used to control the thread to work in a sequential manner. It is important for data security.

Using Semaphores in C language

To use POSIX semaphores, we need to include the <semaphore.h> header file. Follow the below command while compiling with gcc:

gcc program_name.c -lpthread -lrt

Common Used Functions

Following are the usage of common function while working with posix semaphore:

  • sem_wait(): This is called wait/lock for the semaphore.
  • sem_post(): This function unlock the semaphore.
  • sem_init(): This is third level synchronization used for inter-process communication.

Steps to Use POSIX Semaphore in C Language

While using POSIX semaphores in C, it's important to follow these key steps:

  • Include the necessary header files such as <semaphore.h> and <pthread.h>.
  • Initialize the semaphore using sem_init() function by specifying its initial value and scope.
  • To manage synchronization between threads or processes, you can use the sem_wait() and sem_post() functions.
  • At the end, when task is done, destroy the semaphore using sem_destroy() to release the allocated system resources.

Example to Use Semaphore in C

In this example, we will see how to use posix semaphore in C language:

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>

sem_t mutex; // Declare semaphore

// Function that acts like a thread
void* thread(void* arg) { 
   // Wait state    
   sem_wait(&mutex); 
   printf("\nEntered into the Critical Section..\n");
   sleep(3); 
   
   // Critical section
   // Coming out of Critical section
   printf("\nCompleted...\n");
   
   // Release semaphore
   sem_post(&mutex); 
   return NULL; 
}

int main() {
   // initialize semaphore
   sem_init(&mutex, 0, 1); 
   // Declare thread variable
   pthread_t th1, th2; 

   // Create first thread
   pthread_create(&th1, NULL, thread, NULL);
   sleep(2);

   // Create second thread
   pthread_create(&th2, NULL, thread, NULL);

   // Join threads with the main thread
   pthread_join(th1, NULL);
   pthread_join(th2, NULL);
   
   // Destroy the semaphore
   sem_destroy(&mutex);
   return 0;
}

The above code obtained the following output:

Entered into the Critical Section..
Completed...
Entered into the Critical Section..
Completed...
Updated on: 2025-06-11T14:42:30+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements