c++11 use condition variable in signal handler

瘦欲@ 提交于 2021-01-02 05:34:05

问题


Is it safe to use std::condition_variable::notify_one in signal handler? Example:

enum State {
  DoNot,
  Do,
};
State state;
std::mutex mutex;

// worker thread
std::thread th = std::thread([]()
{
    std::unique_lock<std::mutex> lc(mutex);
    cv.wait(lc, []() { return state; });
});

//signal handler
void handler(int sig)
{
    if (sig == SOME_SIG)
    {
        std::unique_lock<std::mutex> lc(mutex);
        state = Do;
        cv.notify_one();
    }
}

回答1:


A C++14 draft standard N4296 says:

[support.runtime]/10 The common subset of the C and C++ languages consists of all declarations, definitions, and expressions that may appear in a well formed C++ program and also in a conforming C program. A POF (“plain old function”) is a function that uses only features from this common subset, and that does not directly or indirectly use any function that is not a POF, except that it may use plain lock-free atomic operations... The behavior of any function other than a POF used as a signal handler in a C++ program is implementation-defined.

Emphasis mine.



来源:https://stackoverflow.com/questions/31521182/c11-use-condition-variable-in-signal-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!