Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need condition variables when we can use two semaphores?

An example of producer and consumer threads is usually given. But this can be done with two semaphores. Why do we need condition variables then?

Example with pthread library:

// write thread
while(1)
{
  sem_wait(&read_sem);
  //put data to queue
  sem_post(&write_sem);
}

// read thread
sem_post(&read_sem);
while(1)
{
  sem_wait(&write_sem);
  //get data from queue
  sem_post(&read_sem);
}
like image 555
FlameWare Avatar asked Oct 31 '25 02:10

FlameWare


1 Answers

An example of producer and consumer threads is usually given. But this can be done with two semaphores. Why do we need condition variables then?

Clearly we do not need condition variables to serve that particular scenario. But CVs are an extremely handy tool, more broadly applicable than semaphores. Anything you can do with semaphores, you can do with the support of one or more CVs, but not the other way around. It is important to teach CV usage as part of any thorough training on multi-threaded programming.

I think, then, that you have gotten the question backwards. A better one would be why a single-producer, single-consumer problem is sometimes chosen as an example for teaching CV usage. And I would say that it's because the problem is simple and serves the purpose, not because it provides a compelling reason to choose a CV-based solution in particular.

like image 105
John Bollinger Avatar answered Nov 04 '25 03:11

John Bollinger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!