I am trying to review concurrency concepts, i.e monitor, semaphores, etc. I've learned that Semaphores are natively not available in C++11 (presumably because it is very error prone) - which is why I am trying to review monitors.
The producer/consumer below already works correctly (to my knowledge), but I am wondering if it is possible/correct to make an optimization and explicitly release the unique_lock, instead of waiting for it to destroy itself.
std::mutex mutex;
std::condition_variable space_in_buffer;
std::condition_variable buffer_empty;
std::queue<int> buffer;
#define MAX_BUFFER_SIZE 10
void produce() {
while (1) {
std::unique_lock<std::mutex> lock(mutex);
if (buffer.size() == MAX_BUFFER_SIZE) {
space_in_buffer.wait(lock);
} else {
// produce
int new_product = rand() % 30;
buffer.push(new_product);
printf("Produced [%d] | Item Count: %lu\n", new_product,
buffer.size());
/*
* Possible optimization to call lock.unlock() here, instead
* of waiting for the unique lock to go out of scope ?
*/
buffer_empty.notify_one();
// potential for extra processing here
}
}
}
void consume() {
while (1) {
std::unique_lock<std::mutex> lock(mutex);
if (buffer.size() == 0) {
buffer_empty.wait(lock);
} else {
// consume
int to_be_consumed = buffer.front();
buffer.pop();
printf("Consumed [%d] | Item Count: %lu\n", to_be_consumed,
buffer.size());
/*
* Possible optimization to call lock.unlock() here, instead
* of waiting for the unique lock to go out of scope ?
*/
space_in_buffer.notify_one();
// potential for extra processing here
}
}
}