C++ 线程在进入sleep 之后唤醒会导致延时不准确,测试达到最大38ms 延时,采用组合睡眠方式,最后延时判断阶段能逼近延时情况。
1 #include <iostream> 2 #include <thread> 3 #include <string> 4 #include <ctime> 5 6 using namespace std; 7 8 bool pass_flg = false; 9 10 void Pt1() 11 { 12 cout << "Pt1线程运行" << endl; 13 clock_t curr_st = clock(); 14 clock_t last_st = clock(); 15 16 while (true) 17 { 18 curr_st = clock(); 19 if ((curr_st - last_st) > 1000) 20 { 21 last_st = curr_st; 22 pass_flg = true; 23 } 24 std::this_thread::sleep_for(std::chrono::milliseconds(10)); //线程睡眠 避免cpu 占用过大 25 } 26 } 27 void Pt2() 28 { 29 cout << "Pt2线程运行" << endl; 30 clock_t curr_st = clock(); 31 clock_t last_st = clock(); 32 33 while (true) 34 { 35 if (pass_flg) 36 { 37 pass_flg = false; 38 39 clock_t tmp_val = 0; 40 41 curr_st = clock(); 42 last_st = curr_st; 43 while (tmp_val < 1000) 44 { 45 curr_st = clock(); 46 tmp_val = (curr_st - last_st); 47 if ((1000 - tmp_val) > 50) 48 { 49 std::this_thread::sleep_for(std::chrono::milliseconds(10)); 50 } 51 } 52 53 cout << "Pt2 print: " << tmp_val << endl; 54 55 } 56 std::this_thread::sleep_for(std::chrono::milliseconds(10)); //线程睡眠 避免cpu 占用过大 57 } 58 } 59 60 //#include<Windows.h> 61 // 62 //void ShowWindow() 63 //{ 64 // cout << "show ..." << endl; 65 //} 66 // 67 //void CALLBACK HideWnd(HWND hwnd, UINT uMsg, UINT idEvent, DWORD dwTime);//回调函数声明 68 // 69 //void CALLBACK HideWnd(HWND hwnd, UINT uMsg, UINT idEvent, DWORD dwTime)//回调函数 70 //{ 71 // ShowWindow(); 72 // KillTimer(hwnd, 1); 73 //} 74 75 int main() 76 { 77 std::thread t1(Pt1); 78 std::thread t2(Pt2); 79 80 //HWND thand; 81 //SetTimer(thand, 1, 1000, HideWnd); 82 83 std::string tmp; 84 std::cin >> tmp; 85 }