CThreadGroupEx多任务多线程,无序执行和有序执行

CThreadGroupEx对thread_group进行了封装,实现了函数执行体的内置,可以很好地控制各个线程。新增任务的任务可以实现有序执行。

#include<ctime>
#include<cstdio>
#include<iostream>
#include<string>
using namespace std;

#include <boost/asio.hpp>  
#include <boost/bind.hpp>  
#include <boost/thread.hpp>  
#include <boost/thread/mutex.hpp>  
using namespace boost;
  
typedef boost::mutex CMutex;  
typedef boost::lock_guard<CMutex> CLockGuardMutex;  
typedef  boost::asio::io_service CIoSrv;
typedef boost::asio::io_service::work CWork;
typedef boost::asio::io_service::strand CStrand;
typedef  boost::thread_group CThreadGroup;


CMutex oMutexConsole;//输出不能共享,互斥访问缓冲区

void Download(int series)
{
	CLockGuardMutex oLockGuardMutex(oMutexConsole);
	cout << "电视剧《神雕侠侣》第" << series << "集" << endl;
	this_thread::sleep(posix_time::seconds(rand()%3));
}

class CThreadGroupEx{
private:
	CIoSrv oIoSrv;//任务队列
	CWork oWork;//无序执行
	CStrand oStrand;//按序执行
	CThreadGroup oThreadGroup;//线程组对象
public:
	CThreadGroupEx() : oWork(oIoSrv), oStrand(oIoSrv){}
	void Start(int threads){//创建线程
		for(int i = 0; i < threads; i++){
			oThreadGroup.create_thread(boost::bind(&CThreadGroupEx::Run, this, i));
		}
	}
	void Stop(){
		oIoSrv.stop();//停止服务
		oThreadGroup.join_all();//等待所有线程退出
	}
	void NewTaskWithoutOrder(){//新增几个任务
		oIoSrv.post(boost::bind(Download, 10));
		oIoSrv.post(boost::bind(Download, 21));
		oIoSrv.post(boost::bind(Download, 32));
		oIoSrv.post(boost::bind(Download, 43));
		oIoSrv.post(boost::bind(Download, 54));
		oIoSrv.post(boost::bind(Download, 65));
		oIoSrv.post(boost::bind(Download, 76));
		oIoSrv.post(boost::bind(Download, 87));
		oIoSrv.post(boost::bind(Download, 98));
	}
	//有序执行的代价是多余的等待
	void NewTaskByOrder(){//新增几个任务
		oStrand.post(boost::bind(Download, 10));
		oStrand.post(boost::bind(Download, 21));
		oStrand.post(boost::bind(Download, 32));
		oStrand.post(boost::bind(Download, 43));
		oStrand.post(boost::bind(Download, 54));
		oStrand.post(boost::bind(Download, 65));
		oStrand.post(boost::bind(Download, 76));
		oStrand.post(boost::bind(Download, 87));
		oStrand.post(boost::bind(Download, 98));
	}
private:
	virtual void Run(int threadno){
		boost::system::error_code oErrCode;
		oIoSrv.run(oErrCode);
	}
};

void main()
{
	srand((unsigned)time(NULL));//设置随机数的种子

	CThreadGroupEx oThreadGroupEx;

	oThreadGroupEx.Start(3);
	//oThreadGroupEx.NewTaskWithoutOrder();
	oThreadGroupEx.NewTaskByOrder();
	this_thread::sleep(posix_time::seconds(30));
	oThreadGroupEx.Stop();
}


猜你喜欢

转载自blog.csdn.net/knightonhourse/article/details/80328080