Wake up a std::thread from usleep

后端 未结 6 1854
被撕碎了的回忆
被撕碎了的回忆 2021-02-14 05:25

Consider the following example:

#include 
#include 
#include 

#include 
#include 

         


        
6条回答
  •  我寻月下人不归
    2021-02-14 06:14

    "Is there a way to tell it from the extern "hey man, wake up!", so that I can join it in a reasonable amount of time?"

    No, there's no way to do so according c++ standard mechanisms.

    Well, to get your thread being woken, you'll need a mechanism that leaves other threads in control of it. Besides usleep() is a deprecated POSIX function:

    Issue 6

    The DESCRIPTION is updated to avoid use of the term "must" for application requirements.

    This function is marked obsolescent.

    IEEE Std 1003.1-2001/Cor 2-2004, item XSH/TC2/D6/144 is applied, updating the DESCRIPTION from "process' signal mask" to "thread's signal mask", and adding a statement that the usleep() function need not be reentrant.

    there's no way you could get control of another thread, that's going to call that function.
    Same thing for any other sleep() functions even if declared from std::thread.

    As mentioned in other answers or comments, you'll need to use a timeable synchronization mechanism like a std::timed_mutex or a std::condition_variable from your thread function.

提交回复
热议问题