40.线程等待固定时间

 1 #include <iostream>
 2 #include <thread>
 3 #include <mutex>
 4 #include <chrono>
 5 #include <condition_variable>
 6 #include <mutex>
 7 #include <Windows.h>
 8 using namespace std;
 9 
10 condition_variable cv;
11 mutex m;
12 bool done = false;
13 
14 void run()
15 {
16     //获取当前时间
17     auto start = chrono::high_resolution_clock::now();
18     auto end = chrono::high_resolution_clock::now() + chrono::seconds(2);
19     unique_lock<mutex> lk(m);
20     while (!done)
21     {
22         //等待到end时间
23         if (cv.wait_until(lk, end) == cv_status::timeout)
24         {
25             done = true;
26             cout << "等待结束";
27         }
28     }
29 }
30 
31 void main()
32 {
33     thread th(run);
34     cin.get();
35 }

 

posted @ 2018-03-12 16:08  喵小喵~  阅读(307)  评论(0编辑  收藏  举报