In this blog post we are going to explore thread synchronization with semaphore in Linux. So my first question is what is semaphore? The dictionary meaning of semaphore is “an apparatus for conveying information by means of visual signals, as a light whose position may be changed”. So by the definition it is obvious that it is related to signaling.

thread synchronization with semaphores in Linux

In Linux semaphore is an programming construct having a counter and two methods. The name of its two operations are sem_wait and sem_post. sem_wait decrements the counter whereas sem_post increments the counter. Followings are the APIs for semaphore in Linux system.

sem_init initializes a semaphore pointer by sem. The second parameter is pshared , if it’s value is 0, then the semaphore is local to the current process. The semaphore might be shared between processes. The last parameter value is used to give an initial value to semaphore.

sem_wait decrements the value of semaphore by one.

sem_post increases the value of semaphore by one.

sem_wait is just like a gatekeeper or guard for threads.  if the value of semaphore is 0, then in this case a thread will be blocked or wait until some other thread would increase the value of semaphore.

Both the operation sem_wait and sem_post are atomic in nature. Atomic nature means , two threads would never interfere with each other if they simultaneously try to increase or decrease the value of a single semaphore by 1.

Example for thread synchronization with semaphores in linux

save the code as sample.c ,compile using ‘gcc -std=c99 -g sample.c -osample -lpthread’.  when we run the sample program , it will print 0 1 2 0 1 2 0 1 2 .

Ref:

http://www.dictionary.com/browse/semaphore




Related Contents to follow