How to create semaphore in Linux
Semaphore is a basic synchronization mechanism and it works as a simple counter which increments on resource allocation and decrements on resource de-allocation. You can refer to the tutorial Semaphore before learning this tutorial.
I will explain how to create counting semaphore in Linux. Counting semaphore is non-negative counter. Semaphore count initializes with a number of free resources. Counter value is incremented when resources are added and decremented when resources are released.
In C language, semaphore parameter and functions are defined in <semaphore.h> header file. Various operations on semaphore are performed by different functions which are defined in semaphore header file. You can initialize semaphore, lock and unlock, release the semaphore etc.
Operations performed on semaphore are done by following functions:
Initialization of semaphore – sem_init ( )
Increment or unlock a semaphore – sem_post ( )
Decrement or lock a semaphore – sem_wait ( )
Destroy a semaphore – sem_destroy ( )
Initialization of semaphore
Semaphore is initialized by sem_init ( ) system call.
Synopsis of sem_init ( ):
#include <semaphore.h>
int sem_init (sem_t *semaphore, int pshared, unsigned int arg);
First argument semaphore points an address of semaphore where it is initializing. Second argument pshared indicates whether the semaphore is shared between threads within process or processes.
If pshared is zero, then semaphore is shared between thread of process and if non zero, then semaphore is shared between processes.
Third argument arg defines an initial value of semaphore. It returns zero on success and returns -1 on error.
Increment a semaphore
A Semaphore is incremented by sem_post ( ) system call.
Synopsis of sem_post ( ):
#include <semaphore.h>
int sem_post (sem_t *semaphore );
sem_post ( ) the incremented semaphore which is pointed by semaphore.(meaning not clear) It returns zero on success and -1 on error.
Decrement a semaphore
A Semaphore is decremented or locked by sem_wait ( ) system call.
Synopsis of sem_wait ( ):
#include <semaphore.h>
int sem_wait (sem_t *semaphore );
The system call sem_wait ( ) decrements the semaphore which is pointed by semaphore. *(line not clear) The system call sem_wait ( ) is blocked when semaphore value is zero and it is unblocked until semaphore is able to decrement. It returns zero on success and -1 on error.
Destroy a semaphore
A Semaphore is destroyed by sem_destroy ( ) system call.
Synopsis of sem_destroy ( ):
#include <semaphore.h>
int sem_destroy (sem_t *semaphore );
The system call sem_destroy ( ) destroys the semaphore which is pointed by semaphore. It returns zero on success and -1 on error.
I will take an example of how semaphore works with program. I created two threads one for read and one for write message. When one thread is active, semaphore is incremented and another thread is waiting for completion.
//******************************Semaphore.c***********************************//
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <stdlib.h>
char msg[1000];
sem_t semaphore;
void * read_message();
void * write_message();
int main()
{
pthread_t thread_r, thread_w;
int result1, result2;
sem_init(&semaphore , 0 , 0);
result1 = pthread_create(&thread_r,NULL,read_message,NULL);
if (result1 == 0)
{
printf (“n Thread 1 created successfullyn”);
}
else
{
perror(“Sorry….Thread 1 is not created!!”n”);
exit(EXIT_FAILURE);
}
result2 = pthread_create(&thread_w,NULL,write_message,NULL);
if (result2 == 0)
{
prin“f(“n Thread 2 created successfull”n”);
}
else
{
perr“r(“Sorry….Thread 2 is not created!!”n”);
exit(EXIT_FAILURE);
}
pthread_join (thread_r,NULL);
pthread_join (thread_w,NULL);
return 0;
}
void * read_message( )
{
while(1)
{
prin“f(“Enter a messa”e:”);
sca“f(”%s”,msg);
sem_post(&semaphore);
}
}
void * write_message( )
{
while(1)
{
sem_wait(&semaphore);
prin“f(“Message i” :”);
prin“f(“%”n”,msg);
prin“f(”n”);
}
}
//******************************Semaphore.c***********************************//
In this code two threads are created for read and write message on screen. Semaphore is initialized with zero value because of no multithreading in program. Attributer pthread also defines zero which indicates the semaphore associated between thread of process.
The function read_message ( ) reads the string from input terminal, unlocks and jump on next write thread. When write thread is executed, sem_wait ( ) blocks the read thread until execution is not completed.
This program is continuous in working and alternative read and write thread executed.
Save the file in directory and compile it. After successful compilation, run the executable file from command terminal. You may refer to the tutorial How to make first C program in Linux if you are not aware of compilation and execution process and also refer to the thread in Linux and How to create thread in Linux.
Here compilation process is different than normal C code because thread is attached with program. Enter the following line for compiling the code which is associated with thread:
gcc –pthread -o sem semaphore.c
Now execute the code by entering following line from command terminal:
./sem
When you execute above line, following output is displayed on screen:
Thread 1 created successfully
Thread 2 created successfully
Enter a message: Enginnersgarage
Message is :ashish
Enter a message:
Note: If you want to terminate program, press ctrl+C key.
Filed Under: Tutorials
Questions related to this article?
👉Ask and discuss on EDAboard.com and Electro-Tech-Online.com forums.
Tell Us What You Think!!
You must be logged in to post a comment.