- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to use POSIX semaphores in C language
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$
- Related Articles
- How to use Pre-defined mathematical function in C language?
- How to implement monitors using semaphores?
- How to use ‘else if ladder’ conditional statement is C language?
- Semaphores in Operating System
- Monitors vs Semaphores
- How to merge to arrays in C language?
- Producer Consumer Problem using Semaphores
- How to define pointer to pointer in C language?
- How to execute a command and get output of command within C++ using POSIX?
- How to access an array element in C language?
- How to access the pointer to structure in C language?
- What is the use of sprintf() and sscanf() functions in C language?
- What is the use of randomize and srand functions in C language?
- How to execute a command and get the output of command within C++ using POSIX?
- POSIX Thread Libraries

Advertisements