Single producer/consumer circular buffer which only blocks consumer

前提是你 提交于 2019-12-05 19:40:24

I can see one problem in this implementation. Consider the following sequence.

  1. Assume buffer is full, but consumer is not yet started. So (head=0, tail=0, sem_val=SIZE).
  2. dequeue() is called from consumer thread. sem_wait() succeeds. So just at that instance (head=0, tail=0, sem_val=SIZE-1). Consumer starts reading ar[0].
  3. Now there is a thread switch. enqueue() is called from producer thread. sem_getvalue() would return SIZE-1. So producer writes at ar[0].

Basically I think you need mutex protection for reading and writing operations. But adding mutex might block the threads. So I am not sure whether you get expected behavior from this logic.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!