-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproducer_consurmer.cpp
More file actions
58 lines (45 loc) · 1.41 KB
/
Copy pathproducer_consurmer.cpp
File metadata and controls
58 lines (45 loc) · 1.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <chrono>
const int MAX_BUFFER_SIZE = 5; // 缓冲区最大容量
std::queue<int> buffer; // 缓冲区
std::mutex mtx;
std::condition_variable cv_producer;
std::condition_variable cv_consumer;
void producer() {
int data = 0;
while (true) {
std::unique_lock<std::mutex> lock(mtx);
cv_producer.wait(lock, []{ return buffer.size() < MAX_BUFFER_SIZE; }); // 缓冲区未满才能生产
// 生产数据
buffer.push(data);
std::cout << "Produced: " << data << std::endl;
data++;
cv_consumer.notify_one(); // 通知消费者
lock.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(100)); // 模拟生产耗时
}
}
void consumer() {
while (true) {
std::unique_lock<std::mutex> lock(mtx);
cv_consumer.wait(lock, []{ return !buffer.empty(); }); // 缓冲区非空才能消费
// 消费数据
int data = buffer.front();
buffer.pop();
std::cout << "Consumed: " << data << std::endl;
cv_producer.notify_one(); // 通知生产者
lock.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(150)); // 模拟消费耗时
}
}
int main() {
std::thread t1(producer);
std::thread t2(consumer);
t1.join();
t2.join();
return 0;
}