如何測(cè)試NotifyAll方法的正確性

小樊
85
2024-09-03 02:28:58

要測(cè)試NotifyAll方法的正確性,您需要?jiǎng)?chuàng)建一個(gè)多線程環(huán)境,使用鎖(例如互斥鎖)和條件變量來(lái)控制線程之間的同步。以下是一個(gè)使用C++11的示例,展示了如何測(cè)試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;

    // 創(chuàng)建5個(gè)工作線程
    for (int i = 0; i < 5; ++i) {
        threads.emplace_back(worker, i);
    }

    // 等待所有線程進(jìn)入等待狀態(tà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;
}

在這個(gè)示例中,我們創(chuàng)建了5個(gè)工作線程,每個(gè)線程都在等待共享值shared_value變?yōu)?。主線程在修改共享值后調(diào)用cv.notify_all(),這將喚醒所有等待的線程。

運(yùn)行此代碼將輸出類似于以下內(nèi)容:

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.

請(qǐng)注意,線程的喚醒順序可能會(huì)有所不同,因?yàn)椴僮飨到y(tǒng)可能會(huì)以不同的方式調(diào)度線程。但是,所有線程最終都應(yīng)該被喚醒并打印“notified”消息。

0