一個線程生成隨機數,另一個線程打印,嚴格交替進行。
boost::mutex mtx;
boost::condition_variable_any cond;
vector buffer;
void producer() {
for (int i=0; i<3; i++) {
boost::unique_lock lock(mtx);
buffer.push_back(rand());
cond.notify_all(); // 通知消費者
cond.wait(lock); // 等待消費者處理完
}
}
void consumer() {
size_t expected = 1;
for (int i=0; i<3; i++) {
boost::unique_lock lock(mtx);
while (buffer.size() != expected) cond.wait(lock); // 條件檢查
cout << buffer.back() << "---" << endl;
++expected;
cond.notify_all(); // 通知生產者繼續
}
}
void task1() { cout << "task1\n"; }
void task2() { cout << "task2\n"; }
int main() {
boost::thread_group grp;
for (int i=0; i<3; i++) grp.create_thread(task1);
grp.add_thread(new boost::thread(task2));
cout << "Thread count: " << grp.size() << endl; // 4
grp.join_all(); // 等待所有線程結束
}
Boost.Thread 提供了現代 C++ 風格的線程同步原語,掌握「鎖 + 條件變量 + 線程組」組合拳,能高效解決多數並發編程問題。