c++线程池 简洁安全的线程池

直接上代码:

#include 
#include 
#include 
#include 
#include 


class fixed_thread_pool {
public:
	explicit fixed_thread_pool(size_t thread_count)               //显示的声明构造函数
		: data_(std::make_shared()) {
		for (size_t i = 0; i < thread_count; ++i) {
			std::thread([data = data_] {
				std::unique_lock lk(data->mtx_);
				for (;;) {
					if (!data->tasks_.empty()) {
						auto current = std::move(data->tasks_.front());
						data->tasks_.pop();
						lk.unlock();
						current();
						lk.lock();
					}
					else if (data->is_shutdown_) {
						break;
					}
					else {
						data->cond_.wait(lk);
					}
				}
			}).detach();
		}
	}

	fixed_thread_pool() = default;
	fixed_thread_pool(fixed_thread_pool&&) = default;

	~fixed_thread_pool() {
		if ((bool)data_) {
			{
				std::lock_guard lk(data_->mtx_);
				data_->is_shutdown_ = true;
			}
			data_->cond_.notify_all();
		}
	}

	//template 
	//void execute(F&& task) {
	//	{
	//		std::lock_guard lk(data_->mtx_);
	//		data_->tasks_.emplace(std::forward(task));
	//	}
	//	data_->cond_.notify_one();
	//}

	//可选参数
	template 
	void execute2(F&& func, Args&&... args) {
		{
			auto  task = std::bind(std::forward(func), std::forward(args)...);
			std::lock_guard lk(data_->mtx_);
			data_->tasks_.emplace(std::forward(task));
		}
		data_->cond_.notify_one();
	}



private:
	struct data {
		std::mutex mtx_;
		std::condition_variable cond_;
		bool is_shutdown_ = false;
		std::queue> tasks_;
	};
	std::shared_ptr data_;
};

测试代码:

#include
#include
#include
#include


void fun()
{
	std::cout << "Work in thread: " << std::this_thread::get_id() << std::endl;
	std::cout << "i am fun" << std::endl;
}

void fun1(int i)
{
	std::cout << "Work in thread: " << std::this_thread::get_id() << std::endl;
	std::cout << "i =" << i << std::endl;

}

int main()
{



	std::shared_ptrthread_pool;
	thread_pool = std::make_shared(500);

	
	for (int i = 0; i < 1000; i++)
	{
		thread_pool->execute2(fun);
		fun();
	}

	for (int i = 0; i < 1000; i++)
	{
		thread_pool->execute2(fun1, 1);
		//fun1(i);
	}


	getchar();


}

你可能感兴趣的:(C++,c++多线程编程)