2016-06-23 121 views
1

我想在特定时间唤醒线程。我可以这样做吗?在指定时间唤醒线程

#include <chrono> 
#include <thread> 
using namespace std::literals::chrono_literals; 
void foo() {} 
int main() 
{ 
    using clock = std::chrono::steady_clock; 
    clock::time_point next_time_point = clock::now() + 20s; 
    foo(); 
    std::this_thread::sleep_until(next_time_point); 
} 

回答

3

你从来不应该使用睡眠。相反,等待条件变量

+0

还要考虑条件变量可以有自相矛盾的唤醒,这要求它们与一个附加条件(例如,你检查一个bool)结合起来。 – Taredon

+0

你有没有一个例子。非常感激! – Damian

+0

你有一个例子在这里http://en.cppreference.com/w/cpp/thread/condition_variable – crn