美文网首页
std::condition_variable的小研究

std::condition_variable的小研究

作者: 叶迎宪 | 来源:发表于2019-02-02 22:29 被阅读0次

问题一:如果notify_one或者notify_all的调用早于wait的调用,则wait会立即返回吗?

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>

std::condition_variable cv;
std::mutex cv_m;

void child()
{
    std::this_thread::sleep_for(std::chrono::seconds(2));

    std::unique_lock<std::mutex> lock(cv_m);
    cv.wait(lock);
    std::cerr << "wait stop!\n";
}

int main()
{
    std::thread t1(child);

    //std::this_thread::sleep_for(std::chrono::seconds(2));
    cv.notify_one();

    t1.join();
}

结果:无论是在vc2015还是在ubuntu,这段程序都会卡死。说明早于wait调用之前的notify,是不会产生任何结果的。
此外,由于是一直卡死,说明spurious wake-up现象没有出现。spurious wake-up的出现可能要更复杂的条件,例如更多的线程在运行,或者线程之间出现更多的资源抢夺

相关文章

网友评论

      本文标题:std::condition_variable的小研究

      本文链接:https://www.haomeiwen.com/subject/cnyesqtx.html