std::thread 在 <thread> 头文件中声明,因此使用 std::thread 时需要包含 <thread> 头文件。

thread 构造函数:

default (1)
thread() noexcept;
initialization (2)
template <class Fn, class... Args>
explicit thread (Fn&& fn, Args&&... args);
copy [deleted] (3)
thread (const thread&) = delete;
move (4)
thread (thread&& x) noexcept;

 

(1). 默认构造函数,创建一个空的 thread 执行对象。

(2). 初始化构造函数,创建一个 thread对象,该 thread 对象可被 joinable,新产生的线程会调用 fn 函数,该函数的参数由 args 给出。

(3). 拷贝构造函数(被禁用),意味着 thread 不可被拷贝构造。

(4). move 构造函数,move 构造函数,调用成功之后 x 不代表任何 thread 执行对象。

注意:可被 joinable 的 thread 对象必须在他们销毁之前被主线程 join 或者将其设置为 detached.

代码:

 1 #include <iostream>
 2 #include <chrono>
 3 #include <thread>
 4 using namespace std;
 5 
 6 void fun1(int n) {
 7     for(int i = 0; i < 5; ++i) {
 8         cout << "Thread " << n << " executing\n";
 9         std::this_thread::sleep_for(std::chrono::milliseconds(10));
10     }
11 }
12 
13 void fun2(int &n) {
14     for(int i = 0; i < 5; ++i) {
15         cout << "Thread 2 executing\n";
16         ++n;
17         std::this_thread::sleep_for(std::chrono::milliseconds(10));
18     }
19 }
20 
21 int main() {
22     int n = 0;
23     std::thread t1;//t1 不是一个线程
24     std::thread t2(fun1, n + 1);//值传参
25     std::thread t3(fun2, std::ref(n));//引用传参
26     std::thread t4(std::move(t3));//将t3的资源转移到t4,此时t3不再是一个线程
27 
28     t2.join();
29     t4.join();
30 
31     cout << "Final valuw of n is " << n << '\n';
32 
33 // 输出:
34 // Thread Thread 2 executing
35 // 1 executing
36 // Thread 2 executing
37 // Thread 1 executing
38 // Thread 2 executing
39 // Thread 1 executing
40 // Thread 2 executing
41 // Thread 1 executing
42 // Thread 2 executing
43 // Thread 1 executing
44 // Final valuw of n is 5
45 
46     return 0;
47 }
View Code

相关文章: