在C++中,可以使用std::condition_variable
和std::mutex
來(lái)實(shí)現(xiàn)線程同步
#include<iostream>
#include<thread>
#include <mutex>
#include<condition_variable>
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void print_id(int id) {
std::unique_lock<std::mutex> lck(mtx);
while (!ready) { // 如果ready為false,則等待
cv.wait(lck); // 當(dāng)前線程被阻塞,等待條件變量被通知
}
// 現(xiàn)在線程繼續(xù)執(zhí)行
std::cout << "thread " << id << '\n';
}
void go() {
std::unique_lock<std::mutex> lck(mtx);
ready = true; // 修改共享變量
cv.notify_all(); // 喚醒所有等待的線程
}
int main() {
std::thread threads[10];
// spawn 10 threads:
for (int i = 0; i < 10; ++i)
threads[i] = std::thread(print_id, i);
std::cout << "10 threads ready to race...\n";
go(); // go!
for (auto &th : threads) th.join();
return 0;
}
在這個(gè)例子中,我們創(chuàng)建了10個(gè)線程,每個(gè)線程都會(huì)執(zhí)行print_id
函數(shù)。這些線程在開(kāi)始時(shí)會(huì)獲取互斥鎖并檢查ready
變量。如果ready
為false
,線程將調(diào)用cv.wait(lck)
進(jìn)入等待狀態(tài),此時(shí)線程會(huì)釋放互斥鎖并被阻塞。當(dāng)go
函數(shù)被調(diào)用時(shí),ready
變量被設(shè)置為true
,并調(diào)用cv.notify_all()
喚醒所有等待的線程。一旦線程收到通知,它將重新獲取互斥鎖并繼續(xù)執(zhí)行。