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

7 篇文章 3 订阅

以下代码的编译调试环境为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

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

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

 

  • 5
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值