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

直接上代码:

#include <mutex>
#include <condition_variable>
#include <functional>
#include <queue>
#include <thread>


class fixed_thread_pool {
public:
	explicit fixed_thread_pool(size_t thread_count)               //显示的声明构造函数
		: data_(std::make_shared<data>()) {
		for (size_t i = 0; i < thread_count; ++i) {
			std::thread([data = data_] {
				std::unique_lock<std::mutex> 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<std::mutex> lk(data_->mtx_);
				data_->is_shutdown_ = true;
			}
			data_->cond_.notify_all();
		}
	}

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

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



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

测试代码:

#include<iostream>
#include<ctime>
#include<cstdlib>
#include<string>


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_ptr<fixed_thread_pool>thread_pool;
	thread_pool = std::make_shared<fixed_thread_pool>(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();


}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值