Wake up a std::thread from usleep

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

Consider the following example:

#include 
#include 
#include 

#include 
#include 

         


        
6条回答
  •  时光取名叫无心
    2021-02-14 06:13

    No, it is not possible using the threads from the standard library.

    One possible workaround is to use condition_variable::sleep_for along with a mutex and a boolean condition.

    #include 
    #include 
    #include 
    
    std::mutex mymutex;
    std::condition_variable mycond;
    bool flag = false;
    
    void sleepy() {
         std::unique_lock lock(mymutex);
         mycond.wait_for( lock,
                          std::chrono::seconds(1000),
                          []() { return flag; } );
    }
    
    int main()
    {
        std :: thread sleepy_thread(sleepy);
    
        {
           std::lock_guard lock(mymutex);
           flag = true;
           mycond.notify_one();
        }
    
        sleepy_thread.join();
    }
    

    Alternatively, you can use the Boost.Thread library, which implements the interruption-point concept:

    #include 
    
    void sleepy()
    {
        // this_thread::sleep_for is an interruption point.
        boost::this_thread::sleep_for( boost::chrono::seconds(1000) );
    }
    
    int main()
    {
        boost::thread t( sleepy );
    
        t.interrupt();
        t.join();
    
    }
    

提交回复
热议问题