C++程序中啟動(dòng)線程的方法
C++11 引入一個(gè)全新的線程庫(kù),包含啟動(dòng)和管理線程的工具,提供了同步(互斥、鎖和原子變量)的方法,我將試圖為你介紹這個(gè)全新的線程庫(kù)。
如果你要編譯本文中的代碼,你至少需要一個(gè)支持 C++11 的編譯器,我使用的是 GCC 4.6.1,需要使用 -c++0x 或者 -c++11 參數(shù)來啟用 C++11 的支持。
啟動(dòng)線程
在 C++11 中啟動(dòng)一個(gè)線程是非常簡(jiǎn)單的,你可以使用 std:thread 來創(chuàng)建一個(gè)線程實(shí)例,創(chuàng)建完會(huì)自動(dòng)啟動(dòng),只需要給它傳遞一個(gè)要執(zhí)行函數(shù)的指針即可,請(qǐng)看下面這個(gè) Hello world 代碼:
#include <thread> #include <iostream> void hello(){ std::cout << "Hello from thread " << std::endl; } int main(){ std::thread t1(hello); t1.join(); return 0; }
所有跟線程相關(guān)的方法都在 thread 這個(gè)頭文件中定義,比較有意思的是我們?cè)谏厦娴拇a調(diào)用了 join() 函數(shù),其目的是強(qiáng)迫主線程等待線程執(zhí)行結(jié)束后才退出。如果你沒寫 join() 這行代碼,可能執(zhí)行的結(jié)果是打印了 Hello from thread 和一個(gè)新行,也可能沒有新行。因?yàn)橹骶€程可能在線程執(zhí)行完畢之前就返回了。
線程標(biāo)識(shí)
每個(gè)線程都有一個(gè)唯一的 ID 以識(shí)別不同的線程,std:thread 類有一個(gè) get_id() 方法返回對(duì)應(yīng)線程的唯一編號(hào),你可以通過 std::this_thread 來訪問當(dāng)前線程實(shí)例,下面的例子演示如何使用這個(gè) id:
#include <thread> #include <iostream> #include <vector> void hello(){ std::cout << "Hello from thread " << std::this_thread::get_id() << std::endl; } int main(){ std::vector<std::thread> threads; for(int i = 0; i < 5; ++i){ threads.push_back(std::thread(hello)); } for(auto& thread : threads){ thread.join(); } return 0; }
依次啟動(dòng)每個(gè)線程,然后把它們保存到一個(gè) vector 容器中,程序執(zhí)行結(jié)果是不可預(yù)測(cè)的,例如:
Hello from thread 140276650997504 Hello from thread 140276667782912 Hello from thread 140276659390208 Hello from thread 140276642604800 Hello from thread 140276676175616
也可能是:
Hello from thread Hello from thread Hello from thread 139810974787328Hello from thread 139810983180032Hello from thread 139810966394624 139810991572736 139810958001920
或者其他結(jié)果,因?yàn)槎鄠€(gè)線程的執(zhí)行是交錯(cuò)的。你完全沒有辦法去控制線程的執(zhí)行順序(否則那還要線程干嗎?)
當(dāng)線程要執(zhí)行的代碼就一點(diǎn)點(diǎn),你沒必要專門為之創(chuàng)建一個(gè)函數(shù),你可以使用 lambda 來定義要執(zhí)行的代碼,因此第一個(gè)例子我們可以改寫為:
#include <thread> #include <iostream> #include <vector> int main(){ std::vector<std::thread> threads; for(int i = 0; i < 5; ++i){ threads.push_back(std::thread([](){ std::cout << "Hello from thread " << std::this_thread::get_id() << std::endl; })); } for(auto& thread : threads){ thread.join(); } return 0; }
在這里我們使用了一個(gè) lambda 表達(dá)式替換函數(shù)指針,而結(jié)果是一樣的。
相關(guān)文章
Visual Studio Community 2022(VS2022)安裝圖文方法
這篇文章主要介紹了Visual Studio Community 2022(VS2022)安裝方法,本文分步驟通過圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-09-09C語言實(shí)現(xiàn)繪制貝塞爾曲線的函數(shù)
貝塞爾曲線,又稱貝茲曲線或貝濟(jì)埃曲線,是應(yīng)用于二維圖形應(yīng)用程序的數(shù)學(xué)曲線。本文將利用C語言實(shí)現(xiàn)繪制貝塞爾曲線的函數(shù),需要的可以參考一下2022-12-12Vscode搭建遠(yuǎn)程c開發(fā)環(huán)境的圖文教程
很久沒有寫C語言了,今天抽空學(xué)習(xí)下C語言知識(shí),接下來通過本文給大家介紹Vscode搭建遠(yuǎn)程c開發(fā)環(huán)境的詳細(xì)步驟,本文通過圖文實(shí)例代碼相結(jié)合給大家介紹的非常詳細(xì),需要的朋友參考下吧2021-11-11