知识链接:
https://www.cnblogs.com/lidabo/p/7852033.html
构造函数如下:
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
#include<thread> #include<chrono> #include <iostream> using namespace std; void fun1(int n) //初始化构造函数 { cout << "Thread " << n << " executing\n"; n += 10; this_thread::sleep_for(chrono::milliseconds(10)); } void fun2(int & n) //拷贝构造函数 { cout << "Thread " << n << " executing\n"; n += 20; this_thread::sleep_for(chrono::milliseconds(10)); } int main() { int n = 0; thread t1; //t1不是一个thread thread t2(fun1, n + 1); //按照值传递 t2.join(); cout << "n=" << n << '\n'; n = 10; thread t3(fun2, ref(n)); //引用 thread t4(move(t3)); //t4执行t3,t3不是thread t4.join(); cout << "n=" << n << '\n'; system("pause"); return 0; }