mirror of
http://106.12.3.193:3000/violeteverisland/learn_cpp.git
synced 2026-03-07 17:17:33 +08:00
51 lines
1.3 KiB
C++
51 lines
1.3 KiB
C++
#include <chrono>
|
|
#include <condition_variable>
|
|
#include <iostream>
|
|
#include <queue>
|
|
#include <thread>
|
|
|
|
int main() {
|
|
std::condition_variable cv;
|
|
std::mutex mtx;
|
|
std::queue<int> q;
|
|
bool finished = false;
|
|
|
|
auto producer = [&]() {
|
|
for (int i = 0; i < 10; i++) {
|
|
std::this_thread::sleep_for(std::chrono::milliseconds(200));
|
|
{
|
|
std::lock_guard<std::mutex> lock(mtx);
|
|
q.push(i);
|
|
std::cout << "Produced: " << i << "\n";
|
|
}
|
|
cv.notify_one();
|
|
}
|
|
{
|
|
std::lock_guard<std::mutex> lock(mtx);
|
|
finished = true;
|
|
}
|
|
cv.notify_all();
|
|
};
|
|
|
|
auto consumer = [&]() {
|
|
while (true) {
|
|
std::unique_lock<std::mutex> lock(mtx);
|
|
cv.wait(lock, [&]() { return !q.empty() || finished; });
|
|
if (!q.empty()) {
|
|
int i = q.front();
|
|
q.pop();
|
|
lock.unlock();
|
|
std::cout << "Consumed: "<< i << "\n";
|
|
std::this_thread::sleep_for(std::chrono::milliseconds(500));
|
|
} else if (q.empty() && finished) {
|
|
break;
|
|
}
|
|
}
|
|
};
|
|
|
|
std::thread t1(producer);
|
|
std::thread t2(consumer);
|
|
t1.join();
|
|
t2.join();
|
|
return 0;
|
|
} |