C++并发 std::thread
生活随笔
收集整理的這篇文章主要介紹了
C++并发 std::thread
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 1. 無參
- 2. 參數傳入
- 3. 輸入輸出參數
- 4. lambda表達式
- 5. 類的成員函數
1. 無參
#include <iostream> #include <thread>void hello() {std::cout << "Hello Concurrent, thread id: " << std::this_thread::get_id() << std::endl; }int main() {std::cout << "Main thread, thread id: " << std::this_thread::get_id() << std::endl;std::thread t(hello);t.join();return 0; }運行結果:
- 包含頭文件 #include <thread> ;
- 創建 std::thread 的實例,傳入hello函數,子線程執行hello函數;
- join 等待子線程完成。 或使用 detach 分離子線程與主線程,使主線程無需等待子線程完成。
2. 參數傳入
#include <iostream> #include <thread> #include <string>void hello_input(std::string str) {std::cout << str << ", hello Concurrent, thread id: " << std::this_thread::get_id() << std::endl; }int main() {std::cout << "Main thread, thread id: " << std::this_thread::get_id() << std::endl;std::thread t2(hello_input, "test");t2.join();return 0; }運行結果:
參數作為 std::thread 對象的第二個參數傳入
3. 輸入輸出參數
#include <iostream> #include <thread> #include <string>void hello_input_output(int a, int b, int& ret) {ret = a + b;std::cout << "a + b: " << ret << ", hello Concurrent, thread id: " << std::this_thread::get_id() << std::endl; }int main() {std::cout << "Main thread, thread id: " << std::this_thread::get_id() << std::endl;int ret = 0;std::thread t3(hello_input_output, 1, 5, std::ref(ret));t3.join();std::cout << "hello_input_output, ret: " << ret << std::endl;return 0; }運行結果:
這里是使用參數引用來作為輸出參數, 使用的時候, std::thread 對象中傳入的輸出參數需要使用 std::ref() 函數加以包裝。
線程庫的內部代碼會把參數的副本當成move-only型別(只能移動,不可復制),這些副本被當成臨時變量,以右值形式傳給新線程上的函數。最終,hello_input_output() 函數調用會收到一個右值作為參數。如果不加 std::ref() 這段代碼會編譯失敗。
加 std::ref() 后, hello_input_output() 函數收到的是ret變量的引用,而不是臨時副本。
4. lambda表達式
#include <iostream> #include <thread>int main() {std::cout << "Main thread, thread id: " << std::this_thread::get_id() << std::endl;std::thread t4([] {std::cout << "lambda, thread id: " << std::this_thread::get_id() << std::endl;});t4.join();return 0; }運行結果:
5. 類的成員函數
#include <iostream> #include <thread> #include <string>class MyClass { public:void do_some_thing(std::string str) {m_strstr = str;std::cout << this << " " << str << ", class member function, thread id: " << std::this_thread::get_id() << std::endl;};std::string getStrr() const { return m_strstr; };private:std::string m_strstr;};int main() {std::cout << "Main thread, thread id: " << std::this_thread::get_id() << std::endl;MyClass myClass;std::thread t5(&MyClass::do_some_thing, &myClass, "test");t5.join();std::cout << &myClass << " " << "myclass.getStrr: " << myClass.getStrr() << std::endl;return 0; }運行結果:
若要將某個類的成員函數設定為線程函數:
- 第一個參數,傳入一個函數指針,指向該成員函數;
- 第二個參數,對象指針&myClass,或者std::ref(myClass)。 如果寫成myClass,不帶&或者std::ref,則創建線程的過程中,myClass被拷貝了一份;
- 第三個及以后的參數,為調用的成員函數的參數。
總結
以上是生活随笔為你收集整理的C++并发 std::thread的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php页面背景url不显示图片,back
- 下一篇: 个人公众号注销方法_微信公众号注销后怎么