I would like to implement a producer/consumer scenario that obeys interfaces that are roughly:
class Consumer { private: vector<char> read(size_t n) { // If the internal buffer has `n` elements, then dequeue them // Otherwise wait for more data and try again } public: void run() { read(10); read(4839); // etc } void feed(const vector<char> &more) { // Safely queue the data // Notify `read` that there is now more data } };
In this case, feed and run will run on separate threads and read should be a blocking read (like recv and fread). Obviously, I will need some kind of mutual exclusion on my deque, and I will need some kind of notification system to inform read to try again.
I hear condition variables are the way to go, but all my multithreading experience lies with Windows and am having a hard time wrapping my head around them.
Thanks for any help!
(Yes, I know it’s inefficient to return vectors. Let’s not get into that.)
This code is not production ready. No error checking is done on the results of any library calls.
I have wrapped the lock/unlock of the mutex in LockThread so it is exception safe. But that’s about it.
In addition if I was doing this seriously I would wrap the mutex and condition variables inside objects so they can cot be abused inside other methods of Consumer. But as long as you take note that the lock must be acquired before you use the condition variable (in any way) then this simple situation can stand as is.
Out of interest have you checked the boost threading library?