#include <iostream>
#include <typeinfo>
#include <string>
#include <memory>
#include <vector>
#include <functional>
#include <thread>
using namespace std;
using namespace placeholders;


//线程类
class Thread
{
public:
	Thread(function<void(int)> func, int no) :_func(func), _no(no) {}
	thread start()
	{
		thread t(_func, _no);// _func(_no)
		return t;
	}
private:
	function<void(int)> _func;
	int _no;
};

//线程池类
class ThreadPool
{
public:
	ThreadPool() {}
	~ThreadPool()
	{
		//释放Thread对象占用的堆资源
		for (int i = 0; i < _pool.size(); ++i)
		{
			delete _pool[i];
		}
	}
	//开启线程池
	void startPool(int size)
	{
		for (int i = 0; i < size; ++i)
		{
			_pool.push_back(
				new Thread(bind(&ThreadPool::runInThread, this, _1), i));
		}

		for (int i = 0; i < size; ++i)
		{
			_handler.push_back(_pool[i]->start());
		}

		for (thread &t : _handler)
		{
			t.join();
		}
	}
private:
	vector<Thread*> _pool;
	vector<thread> _handler;

	//把runInThread这个成员方法充当线程函数  thread   pthread_create
	void runInThread(int id)
	{
		cout << "call runInThread! id:" << id << endl;
	}
};

int main()
{
	ThreadPool pool;
	pool.startPool(10);
	return 0;
}

在这里插入图片描述

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐