I have written the producer - consumer as follows:
void producer(int n)
{
std::unique_lock<std::mutex> lock(mtx);
for (int i = 0; i < n; ++i)
{
cv.wait(lock, [] {return !notified; });
std::cout << "Producing.." << i << std::endl;
Q.push(i);
notified = true;
cv.notify_one();
}
done = true;
}
void consumer()
{
std::unique_lock<std::mutex> lock(mtx);
while (!done)
{
cv.wait(lock, [] {return notified; });
while (!Q.empty())
{
std::cout << "Consuming.." << Q.front() << std::endl;
Q.pop();
cv.notify_all();
notified = false;
}
}
}
int main()
{
auto fut1 = std::async(producer, 20);
auto fut2 = std::async(consumer);
fut1.get();
fut2.get();
system("pause");
}
This I consider to be a rare version (home made ^_^), the difference from well known sources like cppreference is that in producer I do not force thread to sleep, instead I wait for notification from consumer, and in consumer I dont wrap the cv.wait
into while(!notified)
loop. This works perfectly.
Is there something wrong with this approach? Did I miss something?