Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

The C and C++ standards support the concept of signal. However, the C11 standard says that the function signal() cannot be called in multi-threaded environments, or the behavior is undefined. But I think the signal mechanism is by nature for multi-threaded environments.

A quote from the C11 standard 7.14.1.1.7

"Use of this function in a multi-threaded program results in undefined behavior. The implementation shall behave as if no library function calls the signal function."

Any explanations about this?

The following code is self-evident.

#include <thread>
#include <csignal>

using namespace std;

void SignalHandler(int)
{
    // Which thread context here?
}

void f()
{
    //
    // Running in another thread context.
    //
    raise(SIGINT); // Is this call safe?
}

int main()
{
    //
    // Register the signal handler in main thread context.
    //
    signal(SIGINT, SignalHandler);

    thread(f).join();
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
369 views
Welcome To Ask or Share your Answers For Others

1 Answer

But I think the signal mechanism is by nature for multi-threaded environments.

I think this sentence is the central misunderstanding. signal() is a method for inter-process communication, not for inter-thread. Threads share common memory and can therefore communicate via mutexes and control structures. Processes don't have common memory and must make-do with some explicit communication structures like signal() or the filesystem.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...