c++11并发编程历程(5)转移线程所有权

一个特定的执行线程如何在线程实例之间移动,那么线程的所有权如何实现转移呢,直接看例子

#include <iostream>
#include <thread>

class scoped_thread
{
public:
	scoped_thread() {}
	int start(std::thread _t) 
	{
		m_thread = std::move(_t);		
		if (!m_thread.joinable())
			throw std::logic_error("No Thread");
		std::cout << "scoped_thread start " << std::endl;
		return 0;
	}
	~scoped_thread()
	{
		m_thread.join();
	}
	scoped_thread(scoped_thread const &) = delete;
	scoped_thread & operator=(scoped_thread const &) = delete;

private:
	std::thread m_thread;
};

struct func
{
	int &m_i;
	func(int &i) :m_i(i) {}

	int operator()()
	{

		for (int i = 0; i < 10000; ++i)
		{
			int addr = m_i++;
			std::cout << addr << std::endl;
		}
		return 0;
	}
};

int main()
{
	int i = 0;
	func func1(i);
	//func1();
	scoped_thread my_thread;
	my_thread.start(std::thread(func1));
	return 0;
}

运行结果(截取部分):
在这里插入图片描述
std::thread(func1) 开始创建一个新线程,新线程执行一个可调用的函数对象func1;
然后start中将线程所有权转移给类成员变量m_thread,继续执行线程,在析构函数中等待线程执行完成。

单个的线程所有权转移我们看到了,下面再使用vectot来简单拓展一下线程的批量操作

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

void print(int i)
{
  std::cout<<i<<std::endl;
}

int main()
{
  std::vector<std::thread> threads;

  for(unsigned int i = 0; i< 7; ++i)
    threads.push_back(std::thread(print,i));
  std::for_each(threads.begin(),threads.end(),std::mem_fn(&std::thread::join));
}

运行结果如下:
在这里插入图片描述
线程的批量创建与等待。这个例子虽然看着简单,但是是本专栏博客多线程开始迈向自动化管理的第一步。
此处注意for_each里的mem_fn的用法,

人,总是要有一点精神的,不是吗

发布了32 篇原创文章 · 获赞 23 · 访问量 863

猜你喜欢

转载自blog.csdn.net/weixin_40179091/article/details/105488326