Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++11 use condition variable in signal handler

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();
    }
}
like image 274
stima Avatar asked Jul 20 '15 16:07

stima


People also ask

How does condition variable work in C?

Explanation: When you want to sleep a thread, condition variable can be used. In C under Linux, there is a function pthread_cond_wait() to wait or sleep. On the other hand, there is a function pthread_cond_signal() to wake up sleeping or waiting thread. Threads can wait on a condition variable.

What is condition variable in multithreading?

The condition_variable class is a synchronization primitive that can be used to block a thread, or multiple threads at the same time, until another thread both modifies a shared variable (the condition), and notifies the condition_variable . The thread that intends to modify the shared variable has to.

What operations can you use on condition variables?

There are only two operations that can be applied to a condition variable: wait and signal.


1 Answers

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.

like image 112
Igor Tandetnik Avatar answered Oct 21 '22 10:10

Igor Tandetnik