MultiThreading in C Tutorial - Part 8(Semaphore)

API for semaphores:

Header file: #include <semaphore.h>

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

It is used to initialized the semaphore,with the initial value of the semaphore set to the value passed in the third argument..

pshared is used to indicate whether you want to share the semaphore between process or threads.
if pshared value is zero it is shared between threads else it will be shared between processes.

If you are trying to initialize already initialized semaphore,the result is undefined behaviour.

int sem_destroy(sem_t *sem);

Initialized semaphores that are not currently blocked can be destroyed by using sem_destroy api.

int sem_wait(sem_t *sem);

It decrements the value pointed by the semaphore.If the value is greater than zero then the function returns immediately,if the value is zero then it is blocked until the value is greater than zero so that it can decrement it.

int sem_post(sem_t *sem);

sem_post increments(unlocks) the semaphore pointed by sem. If the semaphore's value consequently becomes greater than zero, then another process or thread which is blocked in sem_wait will be woken up and is allowed to lock the semaphore.

On success these API's returns zero else it returns the error number.


Example:

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>

int counter = 0;
pthread_t tid[2];
sem_t sem ;

void *threadFn(void *arg)
{
sem_wait(&sem);
counter += 1;
printf("Job %d started\n", counter);
sleep(1);
printf("Job %d Finished\n", counter);
sem_post(&sem);
pthread_exit(NULL);
}


int main(int argc,char *argv[])
{

int ret, i;
ret = sem_init(&sem, 0, 1);
if (ret != 0) {
perror("Error creating Semaphore\n");
exit(1);
}
for (i = 0; i < 2;i++) {
ret = pthread_create(&tid[i], NULL, threadFn, NULL);
if (ret != 0) {
perror("Error in creating threads\n");
exit(1);
}
}
pthread_join(tid[0], NULL);
pthread_join(tid[1], NULL);
sem_destroy(&sem);
pthread_exit(NULL);

}

O/P:
Job 1 started
Job 1 Finished
Job 2 started
Job 2 Finished

Comments

Popular posts from this blog

bb.utils.contains yocto

make config vs oldconfig vs defconfig vs menuconfig vs savedefconfig

PR, PN and PV Variable in Yocto