c++11 thread类的简单使用
生活随笔
收集整理的這篇文章主要介紹了
c++11 thread类的简单使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一個thread對象就代表一個線程執行,當對象創建完成后,線程函數就開始執行,下面這段話是c++11的thread類介紹。
An initialized thread object?represents an active thread of execution; Such a thread object?is joinable, and has a unique thread id.
A default-constructed (non-initialized)?thread object is?not joinable, and its thread id is common for all non-joinable threads.
A joinable thread becomes not joinable if moved from, or if either join or detach are called on them.
需要注意的是:當一個線程對象是joinable狀態時,對象在析構前需要使用detach或者jion函數。
現在寫代碼證實這段話,加深c++11 thread類的使用,具體代碼如下:
#include "stdafx.h" #include <memory> #include <string> #include <iostream> #include <thread>void pause_thread(int nSleepTime) {//std::cout << "pause for: " << nSleepTime << "\n";std::this_thread::sleep_for(std::chrono::seconds(nSleepTime)); }int main() {//thread1和thread2 是初始化的線程對象,它是joinable狀態并且有唯一的id;std::thread thread1(pause_thread, 1);std::thread thread2(pause_thread, 2);//thread3是未初始化的線程對象,它是非joinable狀態,id不唯一std::thread thread3;//驗證代碼if (thread1.joinable()){std::cout <<"thread1 is joinable" << std::endl;}if (thread2.joinable()){std::cout << "thread2 is joinable" << std::endl;}if (!thread3.joinable()){std::cout << "thread3 is not joinable" << std::endl;}std::cout << "***********分割線*****************\n\n" << std::endl;std::cout << "thread1: " << thread1.get_id() << std::endl;std::cout << "thread2: " << thread2.get_id() << std::endl;std::cout << "thread3: " << thread3.get_id() << std::endl;//thread objects that are joinable shall either be joined// or detached before they are destroyed.thread1.join();thread2.detach();std::cout << "*************分割線****************\n\n" << std::endl;//A joinable thread becomes not joinable if moved from, //or if either join or detach are called on them.if (!thread1.joinable()){std::cout << "thread1 becomes not joinable" << std::endl;}if (!thread2.joinable()){std::cout << "thread2 becomes not joinable" << std::endl;}return 0; }運行結果:
總結
以上是生活随笔為你收集整理的c++11 thread类的简单使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 中国航天员遇到外星人怎么办?载人航天总师
- 下一篇: Ross Young:苹果 iPhone