1

Topic: Question about 2 flows of a read and write in queue

Prompt how to force, please, the second flow to address to queue only when really in queue there are elements for reading? I.e.  2 flows! 1 flow writes down in queue:... while (1) {write (value);} 2 flow reads from queue:... while (1) {read (value);} void write (int value) {mutex.lock (); queue.push (value); mutex.unlock ();} int read () {int res; mutex.lock (); if (! queue.empty ()) {res = queue.front (); queue.pop ();} mutex.unlock ();}

2

Re: Question about 2 flows of a read and write in queue

condition_variable

3

Re: Question about 2 flows of a read and write in queue

Hello, emergenter, you wrote: E> Prompt how to force, please, the second flow to address to queue only when really in queue there are elements for reading? In addition to the right answer the Author: niXman Date: 20.01 00:11: Here so there will be where more bright, if at you a long handling of elements of queue. int read () {int res; decltype (queue) items; mutex.lock (); std:: swap (items, queue); mutex.unlock (); for (const auto& item: items) {//TODO}} As, it is necessary to be careful with conditional variable - if it worked that it does not mean at all that in queue something is. It is necessary to do doubling check. And here implementation in Qt the such does not suffer, though works a bit more slowly.

4

Re: Question about 2 flows of a read and write in queue

Hello, emergenter, you wrote: E> Prompt how to force, please, the second flow to address to queue only when really in queue there are elements for reading? To add a semaphore. The canonical organization of queue looks so class Item; clsss Queue {queue <Item> item_queue; Mutex mutex; Sem sem; public:.... void put (Item item) {{Mutex:: Lock lock (mutex); item_queue.put (item);} sem.give ();} Item get () {sem.take (); {Mutex:: Lock lock (mutex); return item_queue.get ();}}};