Semaphore

I was asked to add this piece of code to a c program which I will execute through the shell:

for(long i = 0; i < NITER; i++)
{ sem_wait( &sema);
count++;
sem_post( &sema); }

I didn't get it, which is the critical section ? if it's "count++" how would a thread wake up in order to enter it if the post comes after this critical section ?.
From my understanding post is the action that wakes up the thread in the queue, or increasing the semaphore by 1 if no threads are waiting.

Exactly what you think it is.

You have it a bit backwards, I think - sem_wait is what's responsible for making threads sleep. If the resource is busy, sem_wait makes you sleep, if the resource is free, it does not.

The first thread to enter the critical section does not sleep and the semaphore is decremented from 1 to 0. The second and third threads cannot decrement the semaphore and are forced to wait instead.

The first thread, which didn't stop, keeps going and eventually runs sem_post, which wakes up the second thread, which runs and eventually runs sem_post, et cetera.

1 Like