13

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?

3
  • Have you searched anywhere for this? Do it! Commented Jul 27, 2012 at 4:25
  • Also google about "busy waiting" Commented Jul 27, 2012 at 7:20
  • possible duplicate of Conditional Variable vs Semaphore Commented Jun 18, 2015 at 12:24

3 Answers 3

22

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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..

1 Comment

Adding a count to a condition variable is pretty simple - you'd do while (count < 1) cond_wait(); cond--; in the waiter and count++; cond_signal(); in the signaller.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.