C++11线程指南(5)--线程的移动语义实现

目录

1. 线程的移动语义

2. 通过引用传递线程参数


1. 线程的移动语义

  基于前面几章介绍的移动语义,我们用它来实现线程。

#include <iostream>
#include <thread>
#include <vector>
#include <algorithm>
#include <cassert>

int main()
{
	std::vector<std::thread> workers;
	for (int i = 0; i < 5; i++) {
		auto t = std::thread([i]()
		{
			std::cout << "thread function: " << i << "\n";
		});
		workers.push_back(std::move(t));
	}
	std::cout << "main thread\n";

	std::for_each(workers.begin(), workers.end(), [](std::thread &t)
	{
		assert(t.joinable());
		t.join();
	});

	return 0;
}

  运行结果为:
main thread
thread function: 2
thread function: 1
thread function: 4
thread function: 3
thread function: 0

  再次运行,结果为:
thread function: 0
thread function: 4
main thread
thread function: 1
thread function: 3
thread function: 2

  接下来对代码进行一些改变。将线程函数task()独立出来。

#include <iostream>
#include <thread>
#include <vector>
#include <algorithm>
#include <cassert>

void task(int i)
{
	std::cout<<"worker : "<<i<<std::endl;
}

int main()
{
	std::vector<std::thread> workers;
	for (int i = 0; i < 5; i++) {
		auto t = std::thread(&task, i);
		workers.push_back(std::move(t));
	}
	std::cout << "main thread" << std::endl;

	std::for_each(workers.begin(), workers.end(), [](std::thread &t)
	{
		assert(t.joinable());
		t.join();
	});

	return 0;
}

  运行结果为:
  worker : worker : 02
  worker : 3
  worker : 1
  main thread
  worker : 4

  再次运行,结果为:
  worker : 0worker : 1
  worker : 4
  main thread
  worker : 3

  worker : 2

2. 通过引用传递线程参数

  下面将线程函数的参数改为引用

void task(int &i)
{
	std::cout << "worker : " << i << "\n";
}

  与此同时,线程的构造函数同样需要相应的修改
  auto t = std::thread(&task, std::ref(i));
  但是,上面程序看似可以工作,不过不是一个好的设计,因为多个线程在同时使用一个指向相同对象的引用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值