标签:std cout windows void C++ sleep 延时 include
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 }
标签:std,cout,windows,void,C++,sleep,延时,include 来源: https://www.cnblogs.com/chenxiaolinembed/p/16359785.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。