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.

int sem_init(sem_t *sem, int pshared, unsigned int value);

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.

int sem_wait(sem_t * sem);

sem_wait decrements the value of semaphore by one.

int sem_post(sem_t * sem);

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


int counter = 0;

sem_t lock;

void* doJobs(void *arg)

    counter = 0;
    for(int i=0; i < 3; i++)
      printf("%d ",counter++);

    return NULL;

int main(void)
    int err;

    pthread_t tid[3];

    if (sem_init(&lock, 0,1) != 0)
        printf("\n mutex initalization failed\n");
        return -1;

    // create three threads
    for(int i=0; i < 3; i++)
        err = pthread_create(&(tid[i]), NULL, doJobs, NULL);
        if (err != 0)
            printf("Fail to create thread :[%s]", strerror(err));

    // join all threads
    for(int i=0; i < 3; i++)
        pthread_join(tid[i], NULL);


    return 0;

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 .


Related Contents to follow