Are std::signal and std::raise thread-safe?

前端 未结 4 1880
粉色の甜心
粉色の甜心 2020-12-18 21:13

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 beha

4条回答
  •  旧巷少年郎
    2020-12-18 21:45

    The C11 standard's statement that "Use of this function in a multi-threaded program results in undefined behavior," refers specifically to the function signal(). So the question is if the use of signal() is done "in a multi-threaded program."

    The term 'multi-threaded program' isn't defined in the C standard as far as I can tell, but I would take it to mean a program in which multiple threads of execution have been created and have not completed. That would mean that at the time signal() is called in your example program the program is not multi-threaded and therefore the program's behavior is not undefined under this requirement.

    (However C++11 requires that "All signal handlers shall have C linkage," [18.10 Other runtime support [support.runtime] p9]. Since your example program uses a handler with C++ linkage the behavior is undefined.)


    As others have pointed out signals aren't intended for communication between threads. For example the C and C++ standards don't even specify what thread they run on. The standard library instead provides other tools for inter-thread communcation, such as mutexes, atomics, etc.

提交回复
热议问题