c++multithreadingqueuereaderwriterlock

Does a single queue with separate reader and writer threads needs locking?


I have a shared queue (implemented using a singleton queue wrapper) and a reader thread and a writer thread. I also have a mechanism to inform the reader thread when writer thread adds elements (enqueue) to the queue. Reader thread dequeue only one element when informed. Is there a necessity of a Read Write Lock in this scenario.

Since writer is only enqueing and reader dequeing I feel like there is no need for a lock, if reader checks the queue size when dequeing.


Solution

  • Since writer is only enqueing and reader dequeing I feel like there is no need for a lock, if reader checks the queue size when dequeing.

    Among other problems that operation alone is already unsafe, when the queue is modified by another thread. In c++, any unsynchronized access to a non-atomic shared variable (with at least one of them is a write) is a data race and hence UB.