要测试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”消息。