Alex Rivera | Logout

pthread_cond_wait versus semaphore

Asked 2008-09-16T09:40:31.653
49

What are the pros / cons of using pthread_cond_wait or using a semaphore ? I am waiting for a state change like this :

pthread_mutex_lock(&cam->video_lock);
while(cam->status == WAIT_DISPLAY) {
    pthread_cond_wait(&cam->video_cond, &cam->video_lock);
}
pthread_mutex_unlock(&cam->video_lock);

Using a properly initialised semaphore, I think I could do it like this :

while(cam->status == WAIT_DISPLAY) {
    sem_wait(&some_semaphore);
}

What are the pros and cons of each method ?

Edit
Report

2 Answers

20

Conditionals let you do some things that semaphores won't.

For example, suppose you have some code which requires a mutex, called m. It however needs to wait until some other thread has finish their task, so it waits on a semaphore called s. Now any thread which needs m is blocked from running, even though the thread which has m is waiting on s. These kind of situations can be resolved using conditionals. When you wait on a conditional, the mutex currently held is released, so other threads can acquire the mutex. So back to our example, and suppose conditional c was used instead of s. Our thread now acquires m, and then conditional waits on c. This releases m so other threads can proceed. When c becomes available, m is reacquired, and our original thread can continue merrily along its way.

Conditional variables also allows you to let all threads waiting on a conditional variable to proceed via pthread_cond_broadcast. Additionally it also allows you to perform a timed wait so you don't end up waiting forever.

Of course, sometimes you don't need conditional variables, so depending on your requirements, one or the other may be better.

answered 2008-09-16T11:15:15.233
5

The 2nd snippet is racy, don't do that.

The other answers have a nice discussion of the relative merits; I'll just add that pthread_cond_broadcast is a clear advantage of condition variables.

Beyond that, I'm just more used to condition variables for that, as they are what you use in Java, even because they help you to avoid races when checking the shared flags.

Indeed, in the 2nd snippet you don't have any lock protecting the read of cam->status, so it is accessed through a data race. Most platforms will let you get away with that in this particular example, but that has undefined semantics, by POSIX and by the memory model of the next C/C++ standards.

In fact, a real race condition is possible if another thread allocates a new cam structure and overwrites cam; the waiting thread might see the update to the 'cam' pointer without seeing the initialization of cam->status. Indeed, the 2nd snippet is asking for trouble, in this case and in general.

http://www.hpl.hp.com/personal/Hans_Boehm/c++mm/

answered 2009-01-12T09:11:45.853

Your Answer