c++11多執行緒程式設計(一):建立執行緒的三種方法
阿新 • • 發佈:2019-02-16
c++11執行緒庫
std::thread::get_id() :成員函式中給出對應執行緒物件的id
std::this_thread::get_id() : 給出當前執行緒的id
如果std::thread物件沒有關聯的執行緒,get_id()將返回預設構造的std::thread::id物件:“not any thread”
std::thread::id也可以表示id
原始的c++標準僅支援單執行緒程式設計,新的c++標準(c++11或c++0x)於2011年釋出,引入了新的執行緒庫。
編譯器要求
Linux: gcc 4.8.1 (完全併發支援)
Windows: Visual Studio 2012 and MingW
在linux下的編譯方法:g++ -std=c++11 sample.cpp -lpthread
在c++11中建立執行緒
在每個c++應用程式中,都有一個預設的主執行緒,即main函式,在c++11中,我們可以通過建立std::thread類的物件來建立其他執行緒,每個std :: thread物件都可以與一個執行緒相關聯。
需包含標頭檔案<thread>
std :: thread物件將執行什麼?
我們可以使用std :: thread物件附加一個回撥,當這個新執行緒啟動時,它將被執行。 這些回撥可以是,
1、函式指標
2、函式物件
3、Lambda函式
執行緒物件可以這樣建立
std::thread thObj(<CALLBACK>)
新執行緒將在建立新物件後立即開始,並且將與已啟動的執行緒並行執行傳遞的回撥。
此外,任何執行緒可以通過在該執行緒的物件上呼叫join()函式來等待另一個執行緒退出。
看一個主執行緒建立單獨執行緒的例子,建立完新的執行緒後,主執行緒將列印一些資訊並等待新建立的執行緒退出。
使用函式指標建立執行緒:
#include <iostream> #include <thread> void thread_function() { for (int i = 0; i < 100; i++) std::cout << "thread function excuting" << std::endl; } int main() { std::thread threadObj(thread_function); for (int i = 0; i < 100; i++) std::cout << "Display from MainThread" << std::endl; threadObj.join(); std::cout << "Exit of Main function" << std::endl; return 0; }
使用函式物件建立執行緒:
#include <iostream>
#include <thread>
class DisplayThread {
public:
void operator ()() {
for (int i = 0; i < 100; i++)
std::cout << "Display Thread Excecuting" << std::endl;
}
};
int main() {
std::thread threadObj((DisplayThread()));
for (int i = 0; i < 100; i++)
std::cout << "Display From Main Thread " << std::endl;
std::cout << "Waiting For Thread to complete" << std::endl;
threadObj.join();
std::cout << "Exiting from Main Thread" << std::endl;
return 0;
}
執行緒間的區分
每個std::thread物件都有一個相關聯的id,可以獲取到std::thread::get_id() :成員函式中給出對應執行緒物件的id
std::this_thread::get_id() : 給出當前執行緒的id
如果std::thread物件沒有關聯的執行緒,get_id()將返回預設構造的std::thread::id物件:“not any thread”
std::thread::id也可以表示id
示例:
#include <iostream>
#include <thread>
void thread_function() {
std::cout << "inside thread :: ID = " << std::this_thread::get_id() << std::endl;
}
int main() {
std::thread threadObj1(thread_function);
std::thread threadObj2(thread_function);
if (threadObj1.get_id() != threadObj2.get_id()) {
std::cout << "Both Threads have different IDs" << std::endl;
}
std::cout << "From Main Thread :: ID of Thread 1 = " << threadObj1.get_id() << std::endl;
std::cout << "From Main Thread :: ID of Thread 2 = " << threadObj2.get_id() << std::endl;
threadObj1.join();
threadObj2.join();
return 0;
}