当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C++ Thread constructor用法及代码示例



描述

它用于构造线程对象。

声明

以下是 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− 函数指针、成员指针或任何类型的 move-constructible 函数对象。

  • 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

相关用法


注:本文由纯净天空筛选整理自 C++ Thread Library - Function constructor。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。