Yes I think its misplaced thinking. What if there are no items in the queue, and reader tries to read while writer tries to write? Everyone needs to be locked out while writer tries to write to the queue. Depending on how your code is written there could be more than one reader at the same time. But writer should have exclusive use of the queue data.
There are several ways to accomplish that. One way is setting up a mutex. Under MS-Windows another way is via CRITICAL_SECTION.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
Yes the reader should also lock with the mutex. I suppose you could have just one queue for all readers, as long as the objects in the queue have something to tell you what message goes to whom. Something like that is what MS-Windows does with the windows messages -- each message contains a handle to the destination window.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
Normally, you do need to lock both the reader and writer such that their operations are mutually exclusing (with a mutex or critical section(windows), personally I would recommend Boost.Thread since it uses the best mechanisms for whatever OS you use). And, if you lock all read and write operations, then there is, of course, no issue with having multiple readers and multiple writers. But be careful not to introduce deadlocks. Also make sure you don't lock for more time than needed, because you can easily destroy performance (i.e. you end up with a number of threads lined-up, sleeping, when they could be doing useful work).
You probably also want to use a condition_variable to wake up the reader when a new element is available (in fact you can use the same mutex in the condition_variable). This is going to avoid needless decisions on how to poll for new elements to read (do you use a tight loop that repeatedly checks for new elements, or do you sleep X amount of time between checks). The condition_variable will allow you to put the reader thread to sleep until the queue has a new element.
Finally, if this is anywhere near to being a performance-sensitive implementation, then there are alternatives that allow you to avoid locking (almost) completely. This article presents a nice and simple lock-free queue implementation. Operating systems often rely on a form of RCU to have lock-free readers in a single-writer / multiple-readers problem.
mike_2000_17
Posting Virtuoso
2,137 posts since Jul 2010
Reputation Points: 1,634
Solved Threads: 457