1 detachios
脫離當前主線程,自由執行,亂序;windows
2 join()數組
等待模式,執行完再執行下一個多線程
3 std::this_thread::get_id() this
獲取當前線程編號spa
4 std::thread::hardware_concurrency()線程
檢測CPU有多少個核心code
1 detachblog
脫離當前主線程,自由執行,亂序;get
2 join()
等待模式,執行完再執行下一個
1 #include <iostream> 2 #include <thread> 3 4 void run(int num) 5 { 6 std::cout << "hello world" << num << std::endl; 7 } 8 9 void main() 10 { 11 std::thread *p[10]; 12 13 for (int i = 0; i < 10; i++) 14 { 15 p[i] = new std::thread(run, i);//循環建立線程 16 //p[i]->join();//等待模式,執行完再執行下一個 17 p[i]->detach();//脫離當前主線程,自由執行,亂序; 18 } 19 20 system("pause"); 21 }
1 join()
等待模式,執行完再執行下一個
2 std::this_thread::get_id()
獲取當前線程編號
3 std::thread::hardware_concurrency()
檢測CPU有多少個核心
1 #include <iostream> 2 #include <thread> 3 #include <windows.h> 4 5 void msg() 6 { 7 MessageBoxA(0, "對話框內容", "對話框標題", 0);//彈出對話框 8 } 9 10 void main() 11 { 12 auto n = std::thread::hardware_concurrency();//檢測CPU有多少個核心 13 std::cout << n << std::endl; 14 15 std::cout << "thread=" << std::this_thread::get_id() << std::endl;//獲取當前線程編號 16 17 std::thread thread1(msg);//建立多線程 18 std::thread thread2(msg); 19 20 thread1.join();//開始執行,同時彈出2個對話框 21 thread2.join(); 22 23 system("pause"); 24 }
std::vector<std::thread *>threads;//建立一個數組,數組的元素數據類型是std::thread *
threads.push_back(new std::thread(msg));//建立線程,並添加到數組
1 #include <iostream> 2 #include <thread> 3 #include <vector> 4 #include <windows.h> 5 6 void msg() 7 { 8 MessageBoxA(0, "對話框內容", "對話框標題", 0);//彈出對話框 9 } 10 11 void main() 12 { 13 std::vector<std::thread *>threads;//建立一個數組,數組的元素數據類型是std::thread * 14 15 for (int i = 0; i < 10; i++) 16 { 17 threads.push_back(new std::thread(msg));//建立線程,並添加到數組 18 } 19 20 for (auto th : threads)//遍歷數組 21 { 22 th->join();//執行數組中的線程 23 } 24 25 system("pause"); 26 }
threads.push_back(new std::thread(msgA, i));//建立線程,並添加到數組,傳入參數i,進行通訊
1 #include <iostream> 2 #include <thread> 3 #include <vector> 4 #include <windows.h> 5 6 void msgA(int num) 7 { 8 std::cout << std::this_thread::get_id() << " num=" << num << std::endl;//獲取當前線程編號 9 MessageBoxA(0, "對話框內容", "對話框標題", 0);//彈出對話框 10 } 11 12 void main() 13 { 14 std::vector<std::thread *>threads;//建立一個數組,數組的元素數據類型是std::thread * 15 16 for (int i = 0; i < 10; i++) 17 { 18 threads.push_back(new std::thread(msgA, i));//建立線程,並添加到數組,傳入參數i,進行通訊 19 } 20 21 for (auto th : threads)//遍歷數組 22 { 23 th->join();//執行數組中的線程 24 } 25 26 system("pause"); 27 }