Here is some code I wrote to understand the semantics of semaphores:
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
sem_t sem;
void *helper(void *arg) {
sem_wait(&sem);
printf("helper woke upn");
}
int main() {
sem_init(&sem, 0, 0);
pthread_t tid;
pthread_create(&tid, NULL, helper, NULL);
sleep(1);
sem_post(&sem);
sem_wait(&sem);
printf("main woke upn");
exit(0);
}
Why does this print
main woke up
rather than this?
helper woke up
If we look at the man pages, it says
If the semaphore’s value consequently becomes greater than zero, then an‐
other process or thread blocked in a sem_wait(3) call will be woken up and proceed to lock the semaphore.
so why is the main thread allowed to proceed instead of the helper thread?
Josh Levi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.