目錄
1、線程的創建
頭文件<thread>,作用域爲標準作用域。
//創建線程對象
thread t1;
//創建線程並啓動線程或是拋出異常
thread t2(ThreadFunction);
//移動語義,t3替代t2當前狀態,並將t2賦值爲nonjionable
thread t3(move(t2));
//將t2的狀態move assign至t1,如果t1是joinable則調用terminate
t1 = move(t3);
//創建線程ID
std::thread::id ID;
2、成員函數
//如果對象是joinable就返回獨一無二的thread::id,反之返回thread::id()
t1.get_id();
//等待關聯線程完成工作,然後令object變成nonjoinable
t1.join();
//解除t和線程之間的關聯,並讓線程繼續運行,並令object變成nonjoinable。不要讓分離的線程訪問程序變量。線程最好是傳值進去
t1.detach();
//判斷對象是否有一個關聯的線程
t1.joinable();
3、this_thread
this_thread::get_id(); //獲取線程ID
this_thread::sleep_for(chrono::seconds(10)); //將某個線程阻塞dur時間段
this_thread::sleep_until(tp); //將某個線程阻塞直到時間點
this_thread::yield(); //建議釋放控制以便重新調度讓下一個線程能夠執行,放棄當前線程創新分配資源。慎用。
4、例子
#include <iostream>
#include <thread>
#include <vector>
#include <string>
#include <sstream>
#include <chrono>
#include <ctime>
#include <iomanip>
using namespace std;
#pragma warning(disable:4996) //去掉安全屬性
void ThreadFunction()
{
cout << "獲得當前線程ID " << this_thread::get_id() << endl;
//線程分離後不可以時間等待
//將某個線程阻塞dur時間段
this_thread::sleep_for(chrono::seconds(10));
time_t time = chrono::system_clock::to_time_t(chrono::system_clock::now());
struct tm * ptm = std::localtime(&time);
cout << "Current time: " << put_time(ptm, "%X") << '\n';
cout << "Waiting for the next minute to begin...\n";
++ptm->tm_min; ptm->tm_sec = 0;
//將某個線程阻塞直到時間點
this_thread::sleep_until(chrono::system_clock::from_time_t(mktime(ptm)));
//建議釋放控制以便重新調度讓下一個線程能夠執行,放棄當前線程創新分配資源
//this_thread::yield();
}
int main()
{
//創建線程對象
thread t1;
//創建線程並啓動線程或是拋出異常
thread t2(ThreadFunction);
//移動語義,t3替代t2當前狀態,並將t2賦值爲nonjionable
thread t3(move(t2));
//銷燬*this,如果object是joinable則調用,std::terminate。
//t3.~thread();
//將t2的狀態move assign至t1,如果t1是joinable則調用terminate
t1 = move(t3);
//判斷對象是否有一個關聯的線程
cout << "對象是否有一個關聯的線程 " << t1.joinable();
//如果對象是joinable就返回獨一無二的thread::id,反之返回thread::id()
t1.get_id();
//等待關聯線程完成工作,然後令object變成nonjoinable
t1.join();
//解除t和線程之間的關聯,並讓線程繼續運行,並令object變成nonjoinable。確保在程序結束前,線程完成任務。
//t1.detach();
system("pause");
}
運行結果:
獲得當前線程ID 15248對象是否有一個關聯的線程 1
Current time: 17:52:25
Waiting for the next minute to begin...
請按任意鍵繼續. . .