How to provide a sequence of interleaving threads to show that a code breaks and doesn't provide perfect synchronization?

前端 未结 2 1484
余生分开走
余生分开走 2021-01-27 16:38

I know what the following code does and I know why it is a broken code for synchronization as it has only one conditional variable while we need two but I don\'t know how to pro

2条回答
  •  时光取名叫无心
    2021-01-27 17:10

    Presuming that put() sets count to 1 and get() sets count to 0, this code is actually fine as long as you have only one producer and one consumer.

    If you have more than one producer, then the pthread_cond_signal() in the producer might wake up one of the other producers instead of a consumer, and then no consumers will proceed. The same problem exists if you have more than one consumer.

    You can fix this either by introducing separate condition variables for empty and full, or by using pthread_cond_broadcast() instead of pthread_cond_signal().

提交回复
热议问题