Semaphore in Pthread

Semaphore is another way to lock a critical section other than mutex which could prevent the #202112061109. It could be used to restrict the number of possible simultaneous accesses to limited amount of resources. The difference between semaphore and mutex is the thread that lock the mutex own the mutex for its entire lifetime. Semaphore does not introduce ownership to the threads that lock or decrement it.

Unlike mutex, the library for semaphore is not couple into <pthread.h>. Instead, we should import it from <semaphore.h>.

The syntax to create, initialise and destroy semaphore is similar to mutex. The keywords are sem_t, sem_init, and sem_destroy. There are two semaphore operations: sem_wait and sem_post. sem_wait is used to check if the semaphore is greater than 0. It will proceed if so, wait in there if not until the value of semaphore is greater than 0. sem_post need to be called after the critical section in order to release the occupied semaphore by incrementing its value. Note their similarity to the pthread_mutex_lock and pthread_mutex_unlock.

sem_t semaphore;

// in the program
sem_init(&semaphore, 0, 4); // This semaphore could be lock by a maximum of 4
                            // threads

// at somewhere
sem_wait(&semaphore); // decrement to 3
sem_post(&semaphore); // increment back to 4

// at the end of the program
sem_destroy(&semaphore);

Inspect the Semaphore’s Value

To inspect the current value of the semaphore, we could call sem_getvalue on it. However, be reminded that the reading of the semaphore’s value is not 202112061109 free in the sense that there is no default safeguard around it. Do not rely on this function to consistently retrieve the value from the semaphore.

int val;

sem_getvalue(&sem, &val);
Links to this page
#multithreading #pthread