C++ 執行緒庫 - 函式建構函式



描述

它用於構造執行緒物件。

宣告

以下是 std::thread::thread 函式的宣告。

thread() noexcept;
template <class Fn, class... Args>
explicit thread (Fn&& fn, Args&&... args);
thread (const thread&) = delete;	
thread (thread&& x) noexcept;

C++11

thread() noexcept;
template <class Fn, class... Args>
explicit thread (Fn&& fn, Args&&... args);
thread (const thread&) = delete;	
thread (thread&& x) noexcept;

引數

  • fn − 它是一個指向函式的指標,指向成員的指標,或任何可移動構造的函式物件。

  • args... − 傳遞給 fn 呼叫的引數。

  • x − 它是一個執行緒物件。

返回值

異常

資料競爭

修改 x。

示例

下面的示例解釋了 std::thread::thread 函式。

#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
#include <functional>
#include <atomic>
 
void f1(int n) {
   for (int i = 0; i < 5; ++i) {
      std::cout << "1st Thread executing\n";
      ++n;
      std::this_thread::sleep_for(std::chrono::milliseconds(10));
   }
}

void f2(int& n) {
   for (int i = 0; i < 5; ++i) {
      std::cout << "2nd Thread executing\n";
      ++n;
      std::this_thread::sleep_for(std::chrono::milliseconds(10));
   }
}
 
int main() {
   int n = 0;
   std::thread t1;
   std::thread t2(f1, n + 1);
   std::thread t3(f2, std::ref(n));
   std::thread t4(std::move(t3));
   t2.join();
   t4.join();
   std::cout << "Final value of n is " << n << '\n';
}

讓我們編譯並執行上述程式,這將產生以下結果:

1st Thread executing
2nd Thread executing
1st Thread executing
2nd Thread executing
1st Thread executing
2nd Thread executing
1st Thread executing
2nd Thread executing
2nd Thread executing
1st Thread executing
Final value of n is 5
thread.htm
廣告

© . All rights reserved.