c++多線程並發可以幫助我們挖掘CPU的性能,在我們的思想中,似乎程序都是順序執行的。這樣的結論是建立在:程序是單線程程序。(比如我們平時寫的hello world程序)。
但是如果程序是多線程的。那么這個結論就不成立了。先上代碼:
1 #include <iostream> 2 #include <thread> 3 #include <chrono> 4 5 void foo() 6 { 7 std::cout << "foo is started\n"; 8 std::this_thread::sleep_for(std::chrono::seconds(1)); 9 std::cout << "foo is done\n"; 10 } 11 12 void bar() 13 { 14 std::cout << "bar is started\n"; 15 std::this_thread::sleep_for(std::chrono::seconds(1)); 16 std::cout << "bar is done\n"; 17 } 18 19 int main() 20 { 21 std::cout << "starting first helper...\n"; 22 std::thread helper1(foo); 23 //std::cout << "thread helper1's ID:" << std::hex << helper1.get_id() <<std::endl; 24 25 std::cout << "starting second helper...\n"; 26 std::thread helper2(bar); 27 //std::cout << "thread helper1's ID:" << std::hex << helper2.get_id() << std::endl; 28 29 std::cout << "waiting for helpers to finish...\n" << std::endl; 30 helper1.join(); 31 helper2.join(); 32 std::cout << "done!\n"; 33 system("pause"); 34 }
程序中: #include <thread>包含了線程類thread,例如程序的22行,就創建了新的線程 helper1,也就是創建新的線程是通過創建線程對象來實現的。也就是:main函數開始,就建立了一個線程,但是這里 又新開辟了一個獨立的線程,而26行所示代碼則又開辟了一個新的線程helper2。我們來直觀看一下,這個程序的結果是什么:
可以看到,程序並沒有在函數foo執行完畢后才執行bar,看起來更像是這兩個線程是同時執行的(你可以去掉創建線程,然后就寫普通的單線程調用實例來看看結果有何不同)
在此,總結三點:
1.多線程編程可以使得程序能夠並發執行
2.多線程創建是通過thread類創建新的對象,也就是一個線程對象就表示為一個新的線程。
3.一個線程被銷毀之前(析構函數被調用之前),必須要先結束該線程,這里的方式是join()方法,該方法會阻塞后續線程的執行。(也就是該線程不執行完,后續無法執行,當然也可以采用非阻塞的方式detach)
關於對多線程並發編程,更多的需要參考下面這位博主的文章:https://www.cnblogs.com/wangguchangqing/p/6134635.html,這篇文章形象而細致的介紹了初步的多線程編程。