c++ 手撕线程池

        最后有完整的代码不想看的可以直接拿代码


        今天给大家带来c++中线程池的实现了,可以添加任务与扩展线程,线程池本身就是一个任务队列与多个线程的组合,在实现的时候我们只需要注意线程安全就可以了

        先看一下本线程池的基本构造

class ThreadPool
{
public:
	ThreadPool(unsigned int threadNum = std::thread::hardware_concurrency());
	~ThreadPool();
	template<typename F, typename... Args>
	auto addTask(F&& f, Args&&... args) -> std::future<decltype(f(args...))>;
	void threadIncrease(unsigned int threadNum);

private:
	void workerThread();

private:
	std::vector<std::thread> threads;
	std::queue<std::function<void()>> tasks;

	bool stop{false};
	std::mutex mutex;
	std::condition_variable cv;
};

        构造很简单一个线程vector和任务队列,还有停止标识符与用来确保线程安全的锁和条件变量,功能实现了初始化话时指定创建的线程数,还有添加任务与扩展线程,std::thread::hardware_concurrency()返回的是实现建议的并发数,通常为 CPU 核心数

        下面我们一一来解释,先看看构造、析构和workerThread函数

inline ThreadPool::ThreadPool(unsigned int threadNum)
{
	for (unsigned int i = 0; i < threadNum; ++i) {
		threads.emplace_back(&ThreadPool::workerThread, this);
	}
	std::cout << "成功创建" << threadNum << "个线程" << std::endl;
}

inline ThreadPool::~ThreadPool()
{
	{
		std::unique_lock<std::mutex> lock(mutex);
		stop = true;
	}
	cv.notify_all();
	for (auto& t : threads) t.join();
}

inline void ThreadPool::workerThread()
{
	std::function<void()> task;
	while (true) {
		{
			std::unique_lock<std::mutex> lock(mutex);
			cv.wait(lock, [this] { return stop || !tasks.empty(); });
			if (stop && tasks.empty()) return;
			task = std::move(tasks.front());
			tasks.pop();
		}
		task();
	}
}

        我们先说最基本的workerThread函数,每个线程内部运行的都是它,其内部定义了一个function<void()>用于运行用户提交的任务,一个死循环保证线程不会自己退出,使用条件变量加智能锁实现了线程安全与无任务时让线程阻塞以免浪费资源,cv.wait的作用是当条件不满足时阻塞当前线程并且释放锁,当被唤醒时会重新判断条件,如果为true重新加锁并恢复线程运行,这时候我们将队列内部的任务取出一个在当前线程运行,这里花括号的作用是限制锁的作用域,减少锁的持有时间,避免执行用户任务时持有锁。
        构造函数很简单就是创建指定数量的线程,每个线程内部运行workerThread,析构函数先是将stop置为true,再调用cv.notify_all();唤醒所有线程,这时线程会先处理完tasks中的任务再结束

        线程的基本运作逻辑看完了,接下来再看一下如何添加任务吧

template<typename F, typename... Args>
inline auto ThreadPool::addTask(F&& f, Args&&...args) -> std::future<decltype(f(args...))>
{
	auto task = std::make_shared<std::packaged_task<decltype(f(args...))()>>(
		std::bind(std::forward<F>(f), std::forward<Args>(args)...)
	);
	{
		std::unique_lock<std::mutex> lock(mutex);
		if (stop) throw std::runtime_error("enqueue on stopped ThreadPool");

		tasks.emplace([task] {(*task)();});
	}
	cv.notify_one();
	return task->get_future();
}

        这个就相对复杂点了,先看函数定义,这里使用了一个普通模板与可变参数模板,普通模板的作用是接受用户传输的可调用对象,可变参数模板用来传入参数,返回值是一个std::future并根据用户提供的任务进行后期类型推导,我们使用decltype来获得函数f(args...)的返回值类型,packaged_task是异步可调用对象的包装器,它能够生成一个std::future,用于获取异步任务的结果,并且会自动捕获异常,用户可通过future.get()获取异常,因此线程池无需额外处理,我们使用bind来创建一个无参对象传递给packaged_task,这里又包了一层shared_ptr的作用是延长packaged_task的生命周期,确保任务执行时对象仍有效,我们将创建好的packaged_task再包装一层Lambda,成为无参无返回值的可调用对象就可以放入tasks了,最后再调用cv.notify_one();唤醒一个线程进行处理。

        这就是c++实现线程池的全部内容了,感谢观看到这里,希望能够给你提供帮助,如果有问题欢迎在评论区说出来。

#pragma once

#include<thread>
#include<iostream>
#include<vector>
#include<mutex>
#include<queue>
#include <functional> 
#include<future>
#include<condition_variable>

class ThreadPool
{
public:
	ThreadPool(unsigned int threadNum = std::thread::hardware_concurrency());
	~ThreadPool();
	template<typename F, typename... Args>
	auto addTask(F&& f, Args&&... args) -> std::future<decltype(f(args...))>;
	void threadIncrease(unsigned int threadNum);

private:
	void workerThread();

private:
	std::vector<std::thread> threads;
	std::queue<std::function<void()>> tasks;

	bool stop{false};
	std::mutex mutex;
	std::condition_variable cv;
};

inline ThreadPool::ThreadPool(unsigned int threadNum)
{
	for (unsigned int i = 0; i < threadNum; ++i) {
		threads.emplace_back(&ThreadPool::workerThread, this);
	}
	std::cout << "成功创建" << threadNum << "个线程" << std::endl;
}

inline ThreadPool::~ThreadPool()
{
	{
		std::unique_lock<std::mutex> lock(mutex);
		stop = true;
	}

	cv.notify_all();
	for (auto& t : threads) t.join();
}

inline void ThreadPool::threadIncrease(unsigned int threadNum)
{
	std::unique_lock<std::mutex> lock(mutex);
	for (unsigned int i = 0; i < threadNum; ++i) {
		threads.emplace_back(&ThreadPool::workerThread, this);
	}
}

inline void ThreadPool::workerThread()
{
	std::function<void()> task;
	while (true) {
		{
			std::unique_lock<std::mutex> lock(mutex);
			cv.wait(lock, [this] { return stop || !tasks.empty(); });
			if (stop && tasks.empty()) return;
			task = std::move(tasks.front());
			tasks.pop();
		}
		task();
	}
}

template<typename F, typename... Args>
inline auto ThreadPool::addTask(F&& f, Args&&...args) -> std::future<decltype(f(args...))>
{
	auto task = std::make_shared<std::packaged_task<decltype(f(args...))()>>(
		std::bind(std::forward<F>(f), std::forward<Args>(args)...)
	);
	{
		std::unique_lock<std::mutex> lock(mutex);
		if (stop) throw std::runtime_error("enqueue on stopped ThreadPool");

		tasks.emplace([task] {(*task)();});
	}
	cv.notify_one();
	return task->get_future();
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值