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).

Example

#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
   sem_post(&mutex);
}
main() {
   sem_init(&mutex, 0, 1);
   pthread_t th1,th2;
   pthread_create(&th1,NULL,thread,NULL);
   sleep(2);
   pthread_create(&th2,NULL,thread,NULL);
   //Join threads with the main thread
   pthread_join(th1,NULL);
   pthread_join(th2,NULL);
   sem_destroy(&mutex);
}

Output

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..

Completed...

Entered into the Critical Section..

Completed...
soumyadeep@soumyadeep-VirtualBox:~/Cpp_progs$
raja
Published on 06-May-2019 13:02:27
Advertisements