-
-
Save dpressel/de9ea7603fa3f20b55bf to your computer and use it in GitHub Desktop.
#ifndef __CONSUMERPRODUCERQUEUE_H__ | |
#define __CONSUMERPRODUCERQUEUE_H__ | |
#include <queue> | |
#include <mutex> | |
#include <condition_variable> | |
/* | |
* Some references in order | |
* | |
* Some code I wrote a long time before C++ 11 to do consumer producer buffers, using 2 condition variables | |
* https://github.com/mdaus/coda-oss/blob/master/modules/c%2B%2B/mt/include/mt/RequestQueue.h | |
* | |
* A great article explaining both 2 condition variable and 1 condition variable buffers | |
* https://en.wikipedia.org/wiki/Monitor_%28synchronization%29#Condition_variables | |
* | |
* C++ 11 thread reference: | |
* http://en.cppreference.com/w/cpp/thread | |
*/ | |
template<typename T> | |
class ConsumerProducerQueue | |
{ | |
std::condition_variable cond; | |
std::mutex mutex; | |
std::queue<T> cpq; | |
int maxSize; | |
public: | |
ConsumerProducerQueue(int mxsz) : maxSize(mxsz) | |
{ } | |
void add(T request) | |
{ | |
std::unique_lock<std::mutex> lock(mutex); | |
cond.wait(lock, [this]() | |
{ return !isFull(); }); | |
cpq.push(request); | |
lock.unlock(); | |
cond.notify_all(); | |
} | |
void consume(T &request) | |
{ | |
std::unique_lock<std::mutex> lock(mutex); | |
cond.wait(lock, [this]() | |
{ return !isEmpty(); }); | |
request = cpq.front(); | |
cpq.pop(); | |
lock.unlock(); | |
cond.notify_all(); | |
} | |
bool isFull() const | |
{ | |
return cpq.size() >= maxSize; | |
} | |
bool isEmpty() const | |
{ | |
return cpq.size() == 0; | |
} | |
int length() const | |
{ | |
return cpq.size(); | |
} | |
void clear() | |
{ | |
std::unique_lock<std::mutex> lock(mutex); | |
while (!isEmpty()) | |
{ | |
cpq.pop(); | |
} | |
lock.unlock(); | |
cond.notify_all(); | |
} | |
}; | |
#endif |
@kobi-ca I think it's to wake up any threads that are waiting in add
since they didn't acquire the lock when they asked to.
Why is unlock required explicitly?
Because you have to unlock before notifying.
I dont think you have to unlock before notifying. IIRC you can do either way but it is more efficient to unlock and notify.
if you notify and then unlock, and the threads runs on different cores, the waiting thread would try to acquire but would fail since the locking thread did not have the opportunity to unlock it. does this make sense?
Is the reason why a lock is needed with a condvar is because a lock is required to test the condition?
I think this program is for single consumer thread. What if there are multiple consumer threads.
Why would someone make a program with locks for single thread?
Im working on a program where there is one producer thread which is writing UDP packets on a shared Queue and there are multiple number of consumer threads , popping data from the shared thread.
why notify_all in consumer?