多執行緒同步問題,都需要用到監視器,用來監視資源是否可用,C++中使用condition_variable,Java中使用Condition來實作同步,
1. 實作思路
- 需要有一個全域變數控制當前該哪個執行緒訪問資源
- 呼叫wait,讓出資源使用權
- 呼叫notify,通知執行緒訪問資源
2. C++實作
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
namespace its {
std::mutex mtx; //往輸出緩沖區列印內容是臨界區,所以不同執行緒間需要互斥
std::condition_variable cv; //監視輸出緩沖區這個資源是否可以被其他執行緒使用
int index = 1; //用來協調執行緒
void print_number() {
std::unique_lock<std::mutex> lck(mtx);
for (int i = 1; i <= 52; i++) {
if (index % 3 == 0) { //當列印了兩個數字后,需要讓字母行程列印
cv.wait(lck);
}
std::cout << i;
index++;
cv.notify_all();
}
}
void print_alphabet() {
std::unique_lock<std::mutex> lck(mtx);
for (char i = 'A'; i <= 'Z'; i++) {
if (index % 3 != 0) { //當列印了一個字母后,需要讓數字行程列印
cv.wait(lck);
}
std::cout << i;
index++;
cv.notify_all();
}
}
}
int main() {
std::thread threads[2];
threads[0] = std::thread(its::print_number);
threads[1] = std::thread(its::print_alphabet);
for (auto &th : threads)
th.join();
std::cout << std::endl;
return 0;
}
3. 參考資料
- 關于執行緒池,看這一篇就夠了!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/3848.html
標籤:其他
上一篇:執行緒池,看這一篇就夠了!
