C++ 多线程:时间控制
生活随笔
收集整理的這篇文章主要介紹了
C++ 多线程:时间控制
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
C++多線程庫中的各個子庫都有各自的時間控制方式,依此來進行多線程程序運行中cpu資源的精確控制。
使用std::chrono時間庫可以提供微妙、毫秒、秒及以上的時間取用,并且能夠獲取當前系統時間。
如下代碼
#include <iostream>
#include <fstream>
#include <mutex>
#include <thread>
#include <future>
#include <deque>using namespace std;int fun1(int n) {int res = 1;for (int i =n; i> 0; --i) {res *= i;}cout << "Result is " << res << endl;return res;
}int main()
{std::thread t1(fun1,6);// 休眠2秒std::this_thread::sleep_for(std::chrono::seconds(2));//休眠靜態時間點,當前線程從當前系統時間點開始 休眠2秒std::chrono::steady_clock::time_point tp = std::chrono::steady_clock::now() + std::chrono::seconds(2);std::this_thread::sleep_until(tp);t1.join();std::mutex mu;std::unique_lock<std::mutex> locker(mu);//condtion_variable條件變量的時間控制std::condition_variable cond;cond.wait_for(locker,std::chrono::seconds(2));cond.wait_until(locker,tp);//promise異步操作獲取共享狀態的時間控制std::promise<int> p;std::future<int> f = p.get_future();f.wait_for(std::chrono::seconds(2));f.wait_until(tp);return 0;
}
總結
以上是生活随笔為你收集整理的C++ 多线程:时间控制的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 求一个带媛字的好听女孩名字!
- 下一篇: linux C 多线程编程