1.3. C++并发(转移线程所有权,简单控制线程数量)

std::thread实例是可以转移的,但是不能复制,因此转移线程的所有权也是很重要的内容点。
案列1:转移线程所有权并且使用类进行线程管理(RAII)
该实例类比前面1.2中提到的thread_guard类不同之处在于管理类不是引用thread实例而是将thread实例所有权转移到了类中。

#include 
class scoped_thread
{
	std::thread t:
public:
	explicit scoped_thread(std::thread t_):
		t(std::move(t_))
	{
		if(!t.joinable())
			throw std::logic_error("No thread");
	}
	~scoped_thread()
	{
		t.join();
	}
	scoped_thread(scoped_thread const&)=delete;
	scoped_thread& operator=(scoped_thread const&)=delete;
};
struct func;
int main()
{
	int some_local_state=1;
	scoped_thread t(std::thread(func(some_local_state)));
	do_something();
	return 0;
}

实例2:简单控制线程数量
使用std::vectorstd::thread是线程迈向自动化管理的第一步

template<typename Iterator, typename T>
struct accumulate_block
{
	void operator()(Iterator first, Iterator last, T& result)
	{
		result = std::accumulate(first, last, result);
	}
};
template<typename Iterator first, Iterator last, T init)
{
	unsigned long const length = std::distance(first, last);
	if(!length)
		return init;
	unsigned long const min_per_thread = 25;
	unsigned long const max_threads = (length+min_per_thread-1)/min_per_thread;
	unsigned long const hard_ware_threads = std::thread::hardware_concurrency();
	unsigned long const num_threads = std::min(hardware_threads!=0?hardware_threads:2,max_threads);
	unsigned long const block_size=length/num_threads;
	std::vector<T> results(num_threads);
	std::vector<std::thread> threads(num_threads-1);
	Iterator block_start=first;
	for(unsigned long i=0;i<(num_threads-1); ++i)
	{
		Iterator block_end = block_start;
		std::advance(block_end, block_size);
		thread[i]=std::thread(accumulate_block<Iterator, T>(), block_start, block_end, std::ref(results[i]));
		block_start = block_end;
	}
	accumulate_block<Iterator, T>()(block_start, last, results[num_threads-1]);
	std::for_each(threads.begin(), threads.end(), std::mem_fn(&std::thread::join));
	return std::accumulate(results.begin(), results.end(), init);
}

实例3:标识线程
用来区别线程,线程标识符都是std::thread::id类型,可以通过std::thread对象调用get_id()来获得,或者调用std::this_thread::get_id()获得。很多情况下,std::thread::id可以用来作为线程的通用标识符

std::thread::id master_thread;
void some_core_part_of_algorithm()
{
	if(std::this_thread::get_id()==master_thread)
	{
		do_master_thread_work();
	}
}

你可能感兴趣的:(c++学习,多线程thread)