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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
|
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
class ThreadSafeQueue
{
private:
std::queue<int> m_Queue;
std::mutex m_Mutex;
std::condition_variable m_Condition;
public:
void Push(int value)
{
std::lock_guard<std::mutex> lock(m_Mutex);
m_Queue.push(value);
std::cout << "Pushed: " << value << std::endl;
m_Condition.notify_one(); // 通知等待的线程
}
int Pop()
{
std::unique_lock<std::mutex> lock(m_Mutex);
// 等待直到队列不为空
m_Condition.wait(lock, [this] { return !m_Queue.empty(); });
int value = m_Queue.front();
m_Queue.pop();
std::cout << "Popped: " << value << std::endl;
return value;
}
bool TryPop(int& value, std::chrono::milliseconds timeout)
{
std::unique_lock<std::mutex> lock(m_Mutex);
if (m_Condition.wait_for(lock, timeout, [this] { return !m_Queue.empty(); }))
{
value = m_Queue.front();
m_Queue.pop();
std::cout << "Try popped: " << value << std::endl;
return true;
}
std::cout << "Try pop timeout" << std::endl;
return false;
}
size_t Size()
{
std::lock_guard<std::mutex> lock(m_Mutex);
return m_Queue.size();
}
};
void Producer(ThreadSafeQueue& queue, int start, int count)
{
for (int i = 0; i < count; ++i)
{
queue.Push(start + i);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
void Consumer(ThreadSafeQueue& queue, int consumeCount)
{
for (int i = 0; i < consumeCount; ++i)
{
int value = queue.Pop();
std::this_thread::sleep_for(std::chrono::milliseconds(150));
}
}
int main()
{
std::cout << "=== Condition Variable Example ===" << std::endl;
ThreadSafeQueue queue;
// 创建生产者和消费者线程
std::thread producer1(Producer, std::ref(queue), 1, 5);
std::thread producer2(Producer, std::ref(queue), 100, 3);
std::thread consumer1(Consumer, std::ref(queue), 4);
std::thread consumer2(Consumer, std::ref(queue), 4);
// 等待所有线程完成
producer1.join();
producer2.join();
consumer1.join();
consumer2.join();
std::cout << "Remaining items in queue: " << queue.Size() << std::endl;
return 0;
}
|