Last active
March 18, 2024 19:55
-
-
Save iikuy/8115191 to your computer and use it in GitHub Desktop.
producer-consumer in C++11
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <thread> | |
#include <iostream> | |
#include <queue> | |
std::mutex mx; | |
std::condition_variable cv; | |
std::queue<int> q; | |
bool finished = false; | |
void producer(int n) { | |
for(int i=0; i<n; ++i) { | |
{ | |
std::lock_guard<std::mutex> lk(mx); | |
q.push(i); | |
std::cout << "pushing " << i << std::endl; | |
} | |
cv.notify_all(); | |
} | |
{ | |
std::lock_guard<std::mutex> lk(mx); | |
finished = true; | |
} | |
cv.notify_all(); | |
} | |
void consumer() { | |
while (true) { | |
std::unique_lock<std::mutex> lk(mx); | |
cv.wait(lk, []{ return finished || !q.empty(); }); | |
while (!q.empty()) { | |
std::cout << "consuming " << q.front() << std::endl; | |
q.pop(); | |
} | |
if (finished) break; | |
} | |
} | |
int main() { | |
std::thread t1(producer, 10); | |
std::thread t2(consumer); | |
t1.join(); | |
t2.join(); | |
std::cout << "finished!" << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How producer will come to know that consumer has done its job in case consumer is scheduled for long time? This situation may arise as below