user1184900
user1184900

Reputation: 161

Difference between a semaphore and a conditional variable

I am implementing conditional wait, and both semaphore or conditional varible can be used to implement it. Is there any difference between the two? More specifically from the performance point of view?

I have heard that when a thread waits on a conditional variable it is not scheduled until it is signaled. This ensures that it does not consume CPU cycle. But this is not true for a semaphore and a semaphore will consume CPU cycle even if it is waiting?

Upvotes: 13

Views: 13709

Answers (3)

S Prakash
S Prakash

Reputation: 1

conditional variable and binary semaphore both block thread until specified signaled condition true , and both are same you can use any one but conditional varibale always use with mutex . in both cases you scheduled only by signal without it you can not scheduled . But in case to maintain number of resources in this case you use counting semaphore . Both are not consume cpu when you use mutex.

Upvotes: 0

Martin James
Martin James

Reputation: 24887

A semaphore has extra state - a count of units held - as well as a queue for threads waiting on it, so allowing a sema to, say, record how many times it has been signaled even if there is no thread currently waiting on it. If a thread loops around a semaphore wait() and the semaphore is signaled N times, the thread will eventually loop N times, even if the thread is sometimes busy when the sema is signaled - very useful for producer-consumer queues.

A condvar does not have this extra count state, but it can release a lock that it is bound to until a thread signals it - very useful for producer-consumer queues.

Sometimes, I wish for a combination of the two - a condvar with a count, but this does not seem to to be forthcoming from OS developers :(

A semaphore and condvar are the same in that they are both synchro primitives. Apart from that..

Upvotes: 3

perreal
perreal

Reputation: 98088

If all of your threads are waiting for some event, e.g., submission of a task, then you can wake them all up by using a condition variable upon an event.

If you have a limited resource, say 10 pages of memory reserved for your threads, then you will need them to wait until a page is available. When this happens, you will need to let just one thread start execution. In this case you can use a semaphore unlock up as many threads as available pages.

Upvotes: 22

Related Questions