要測試NotifyAll
方法的正確性,您需要創建一個多線程環境,使用鎖(例如互斥鎖)和條件變量來控制線程之間的同步。以下是一個使用C++11的示例,展示了如何測試NotifyAll
方法:
#include<iostream>
#include<thread>
#include <mutex>
#include<condition_variable>
#include<vector>
std::mutex mtx;
std::condition_variable cv;
int shared_value = 0;
void worker(int id) {
std::unique_lock<std::mutex> lock(mtx);
std::cout << "Thread " << id << " is waiting."<< std::endl;
cv.wait(lock, [] { return shared_value == 1; });
std::cout << "Thread " << id << " is notified."<< std::endl;
}
int main() {
std::vector<std::thread> threads;
// 創建5個工作線程
for (int i = 0; i < 5; ++i) {
threads.emplace_back(worker, i);
}
// 等待所有線程進入等待狀態
std::this_thread::sleep_for(std::chrono::seconds(1));
// 修改共享值并通知所有線程
{
std::unique_lock<std::mutex> lock(mtx);
shared_value = 1;
}
cv.notify_all();
// 等待所有線程完成
for (auto& t : threads) {
t.join();
}
return 0;
}
在這個示例中,我們創建了5個工作線程,每個線程都在等待共享值shared_value
變為1。主線程在修改共享值后調用cv.notify_all()
,這將喚醒所有等待的線程。
運行此代碼將輸出類似于以下內容:
Thread 0 is waiting.
Thread 1 is waiting.
Thread 2 is waiting.
Thread 3 is waiting.
Thread 4 is waiting.
Thread 0 is notified.
Thread 1 is notified.
Thread 2 is notified.
Thread 3 is notified.
Thread 4 is notified.
請注意,線程的喚醒順序可能會有所不同,因為操作系統可能會以不同的方式調度線程。但是,所有線程最終都應該被喚醒并打印“notified”消息。