boost::thread编程-线程组

本文介绍如何利用thread_group类管理一组线程,包括创建、添加、删除线程,以及对线程进行等待或中断操作。通过实例演示了如何在主线程中创建多个子线程并执行特定任务,最后确保所有线程完成工作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

thread库提供thread_group类用于管理一组线程,就像一个线程池,它内部使用std::list<thread*>来容纳thread对象,类摘要如下:

class thread_group::private noncopyable
{
public:
	template<typename F>;
	thread* create_thread(F threadfunc);
	void add_thread(thread* thrd);
	void remove_thread(thread* thrd);
	void join_all();
	void interrupt_all();
	int size() const;
};
成员函数create_thread是一个工厂函数,可以创建thread对象并运行线程,同时加入到内部的list。我们也可以在thread_group对象外部创建线程,然后使用add_thread加入线程组。
如果不需要某个线程,可以使用remove_thread删除线程组里的thread对象。
join_all()、interrupt_all()用来对list里的所有线程对象进行操作,等待或中断这些线程。

#include "stdafx.h"
#include <iostream>
#include <boost/thread.hpp>
#include <boost/atomic.hpp>

boost::mutex io_mu;//io流操作锁

void printing(boost::atomic_int &x,const std::string &str)
{
	for(int i=0;i<5;++i)
	{
		boost::mutex::scoped_lock lock(io_mu);//锁定io流操作
		std::cout<<str<<++x<<std::endl;
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	boost::atomic_int x(0);
	
	boost::thread_group tg;
	tg.create_thread(boost::bind(printing,ref(x),"hello"));
	tg.create_thread(boost::bind(printing,ref(x),"hi"));
	tg.create_thread(boost::bind(printing,ref(x),"boost"));
	tg.join_all();
	getchar();
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值