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);
}
                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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With