C++ 多线程:时间控制
生活随笔
收集整理的這篇文章主要介紹了
C++ 多线程:时间控制
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
C++多線程庫(kù)中的各個(gè)子庫(kù)都有各自的時(shí)間控制方式,依此來(lái)進(jìn)行多線程程序運(yùn)行中cpu資源的精確控制。
使用std::chrono時(shí)間庫(kù)可以提供微妙、毫秒、秒及以上的時(shí)間取用,并且能夠獲取當(dāng)前系統(tǒng)時(shí)間。
如下代碼
#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));//休眠靜態(tài)時(shí)間點(diǎn),當(dāng)前線程從當(dāng)前系統(tǒng)時(shí)間點(diǎn)開(kāi)始 休眠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條件變量的時(shí)間控制std::condition_variable cond;cond.wait_for(locker,std::chrono::seconds(2));cond.wait_until(locker,tp);//promise異步操作獲取共享狀態(tài)的時(shí)間控制std::promise<int> p;std::future<int> f = p.get_future();f.wait_for(std::chrono::seconds(2));f.wait_until(tp);return 0;
}
總結(jié)
以上是生活随笔為你收集整理的C++ 多线程:时间控制的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 求一个带媛字的好听女孩名字!
- 下一篇: 走下去走下去是哪首歌啊?