转移线程所有权

std::thread对象的容器,如果这个容器是移动敏感的(比如,标准中的std::vector<>),那么移动操作同样适用于这些容器。了解这些后,就可以写出类似清单2.7中的代码,代码量产了一些线程,并且等待它们结束。

清单2.7 量产线程,等待它们结束

点击查看代码
struct funcStruct
{
	int m_i;
	funcStruct(int i):m_i(i) {}
	void operator()()
	{
		for (int i = 0; i < 10; i++)
		{
			cout << m_i << endl;
		}
	}
};

void f()
{
  std::vector<std::thread> threads;
  for(unsigned i=0; i < 20; ++i)
  {
    threads.push_back(std::thread(funcStruct(i))); // 产生线程
  } 
  std::for_each(threads.begin(),threads.end(),
                  std::mem_fn(&std::thread::join)); // 对每个线程调用join()
}
posted @ 2021-09-05 12:49  youlj  阅读(34)  评论(0)    收藏  举报