In this chapter we shall learn about:
1. Introduction
2. Working of POSIX semaphore
3. API’s used in POSIX semaphore
4. Example for POSIX semaphore
Introduction:
In previous chapter we learned about SysteV semaphore. In this chapter we shall learn about POSIX semaphore.
Working of POSIX semaphore:
1. There are 2 operations related to semaphore: wait and post.
2. Post will increase the semaphore count by 1.
3. For wait: if the semaphore value is > 0, then semaphore is decrement by 1.
4. If the semaphore value is 0, the caller will be blocked until the semaphore value is larger than 0, then it will be decremented by 1.
To use POSIX semaphore, include below header file:
#include <semaphore.h>
A semaphore is declared as below:
sem_t sem;
Below are some of the functions used in semaphores
1. sem_init()
Prototype: int sem_init(sem_t * sem, int pshared, unsigned int value);
It will initialize a semaphore.
The initial value of the semaphore will be the “value”
2. sem_wait()
Prototype: int sem_wait(sem_t * sem);
This function decrements the semaphore referred to, by the sem argument.
3. sem_trywait()
sem_trywait() function decrements the semaphore if the semaphore’s value is greater than zero, otherwise the function simply returns.
4. sem_post()
sem_post() function increments the semaphore referenced by the sem argument.
5. sem_destroy()
sem_destroy() function destroys the unnamed semaphore referred to by the sem argument.
Example for POSIX semaphore:
#include <stdio.h> #include <pthread.h> #include <semaphore.h> #include <unistd.h> sem_t sem; void* thread(void* arg) { //wait sem_wait(&sem); printf("\nEntered critical section\n"); //critical section sleep(4); printf("\nExiting critical section\n"); sem_post(&sem); } int main() { sem_init(&sem, 0, 1); pthread_t t1,t2; pthread_create(&t1,NULL,thread,NULL); sleep(2); pthread_create(&t2,NULL,thread,NULL); pthread_join(t1,NULL); pthread_join(t2,NULL); sem_destroy(&sem); return 0; }
Output:
Entered critical section Exiting critical section Entered critical section Exiting critical section
The output is not:
Entered critical section Entered critical section Exiting critical section Exiting critical section