c++11并发编程一(std::thread之:thread构造函数)

以下代码的编译调试环境为Win7+vs2017

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

std::thread 构造方法

(1)默认构造函数 thread() noexcept;
(2)初始化构造函数 template <class Fn, class... Args>
(3)拷贝构造函数 thread (const thread&) = delete;
(4)move构造函数 thread (thread&& x) noexcept;

(1)默认构造函数:创建一个空thread对象,该对象非joinable

(2)初始化构造函数:创建一个thread对象,该对象会调用Fn函数,Fn函数的参数由args指定,该对象是joinable的

(3)拷贝构造函数:被禁用,意味着thread对象不可拷贝构造

(4)move构造函数:移动构造,执行成功之后x失效,即x的执行信息被移动到新产生的thread对象,该对象非joinable

下面代码示例演示了各个构造函数的用法:

#include <iostream>
#include <thread>
#include <chrono>


void f1(int n)
{
	for (int i = 0; i < 5; ++i) {
		std::cout << "Thread 1: i = " << i << std::endl;
		std::this_thread::sleep_for(std::chrono::milliseconds(10));
	}
}

void f2(int& n)
{
	for (int i = 0; i < 5; ++i) {
		std::cout << "Thread 2: i = " << i << std::endl;
		++n;
		std::this_thread::sleep_for(std::chrono::milliseconds(10));
	}
}

int main()
{
	int n = 0;
	std::thread t1; // t1 is not a thread
	
	std::thread t2(f1, n + 1); // pass by value
	std::thread t3(f2, std::ref(n)); // pass by reference
	std::thread t4(std::move(t3)); // t4 is now running f2(). t3 is no longer a thread
	//t3.join();  崩溃
	//t1.join();  崩溃
	t2.join();
	t4.join();
	std::cout << "Final value of n is " << n << std::endl;
}

关于一个thread对象是否是joinable:

如果一个线程正在执行,那么它是jionable的

下列任一情况,都是非joinable:

A:默认构造器构造的。

B:通过移动构造获得的。

C:调用了join或者detach方法的。

其他成员函数

获取线程id

当前线程和子线程分离 ,不必等待子线程结束,即子线程变成守护线程

当前线程阻塞等待子线程结束

猜你喜欢

转载自blog.csdn.net/weixin_44843859/article/details/112170599
今日推荐