C++线程池,将类方法引入线程池

C++线程池,将类方法引入线程池

使用线程的改变可以提高速度。但是如果一味的提升速度而不断的申请线程,则可能会出现计算机资源耗尽的情况。所以提出线程池的概念。

线程池的概念是提前申请一块内存用于保存一定数量的线程,然后根据任务分配线程。如果任务数量大于线程池中线程的数量,则可以引入队列等概念,将任务排队。直到出现空闲线程时,再根据队列中任务的优先级,将任务分配给线程。

如果使用动态线程,申请线程空间需要时间,而且可能会出现线程过度掠夺资源情况。所以在有较多线程时尽量使用线程池进行优化。

1. 建立线程池类

线程池类参考博客:

C++实现线程池

类代码如下所示:

// ThreadPool.h
#ifndef THREAD_POOL_H
#define THREAD_POOL_H

#include <vector>
#include <queue>
#include <memory>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
#include <functional>
#include <stdexcept>
//#include "source/AStar.hpp"
class ThreadPool {

public:
	ThreadPool(size_t);                          //构造函数
	template<class F, class... Args>             //类模板
	auto enqueue(F&& f, Args&&... args)->std::future<typename std::result_of<F(Args...)>::type>;//任务入队
	~ThreadPool();                              //析构函数

private:
	std::vector< std::thread > workers;            //线程队列,每个元素为一个Thread对象
	std::queue< std::function<void()> > tasks;     //任务队列,每个元素为一个函数对象    

	std::mutex queue_mutex;                        //互斥量
	std::condition_variable condition;             //条件变量
	bool stop;                                     //停止
};

// 构造函数,把线程插入线程队列,插入时调用emplace_back(),用匿名函数lambda初始化Thread对象
inline ThreadPool::ThreadPool(size_t threads) : stop(false) {

	for (size_t i = 0; i < threads; ++i) {
		workers.emplace_back([this]() {
			for (;;)
			{
				// task是一个函数类型,从任务队列接收任务
				std::function<void()> task;
				{
					//给互斥量加锁,锁对象生命周期结束后自动解锁
					std::unique_lock<std::mutex> lock(this->queue_mutex);

					//(1)当匿名函数返回false时才阻塞线程,阻塞时自动释放锁。
					//(2)当匿名函数返回true且受到通知时解阻塞,然后加锁。
					this->condition.wait(lock, [this] { return this->stop || !this->tasks.empty(); });

					if (this->stop && this->tasks.empty())
						return;

					//从任务队列取出一个任务
					task = std::move(this->tasks.front());
					this->tasks.pop();
				}                            // 自动解锁
				task();                      // 执行这个任务
			}
		}
		);
	}

}

// 添加新的任务到任务队列
template<class F, class... Args>
auto ThreadPool::enqueue(F&& f, Args&&... args)
-> std::future<typename std::result_of<F(Args...)>::type>
{
	// 获取函数返回值类型        
	using return_type = typename std::result_of<F(Args...)>::type;

	// 创建一个指向任务的智能指针
	auto task = std::make_shared< std::packaged_task<return_type()> >(
		std::bind(std::forward<F>(f), std::forward<Args>(args)...)
		);

	std::future<return_type> res = task->get_future();
	{
		std::unique_lock<std::mutex> lock(queue_mutex);  //加锁
		if (stop)
			throw std::runtime_error("enqueue on stopped ThreadPool");

		tasks.emplace([task]() { (*task)(); });          //把任务加入队列
	}                                                   //自动解锁
	condition.notify_one();                             //通知条件变量,唤醒一个线程
	return res;
}

// 析构函数,删除所有线程
inline ThreadPool::~ThreadPool()
{
	{
		std::unique_lock<std::mutex> lock(queue_mutex);
		stop = true;
	}
	condition.notify_all();
	for (std::thread &worker : workers)
		worker.join();
}

#endif

参考博客中有对代码以及使用方法的详细解读,详细请阅读参考博客。

2. 使用其他类定义的方法进行多线程

上述的参考博客中使用线程池的方法是使用函数。

// main.cpp
#include <iostream>
#include "ThreadPool.h"
 
void func()
{
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    std::cout<<"worker thread ID:"<<std::this_thread::get_id()<<std::endl;
}
 
int main()
{
    ThreadPool pool(4);
    while(1)
    {
       pool.enqueue(fun);
    }
}

可以看出,声明ThreadPool类后,将调用的函数引入队列中即可使用多线程。但如果使用的是类中的方法则会报错。

// main.cpp
#include <iostream>
#include "ThreadPool.h"
#include "source/AStar.hpp"
 
int main()
{
    ThreadPool pool(4);
    AStar::Generator generator;
    
    for (int i = 0; i < end.size(); ++i) {
		pool.enqueue(generator.findPath, start, end[i], upper_left, lower_right, alpha);
	}
}

上述代码隐藏了Astar.hpp代码的使用,其实现的是使用A*算法求解路径。pool.enqueue()中的第一个参数是多线程的函数,第二个参数以后是多线程函数的参数。

上述代码会出现错误。

在这里插入图片描述

倘若将代码加上&,则会报错。

pool.enqueue(&generator.findPath, start, end[i], upper_left, lower_right, alpha);

在这里插入图片描述

3. 解决类对象方法错误

查阅相关资料,得到结果。参考博客为:

类成员函数作为函数参数出现error C3867:非标准语法;请使用“&”来创建指向成员的指针

错误原因主要是因为类对象中有this指针,而泛函中不能使用this指针(线程池的类实现中使用了模板类)。

所以使用另一个类的函数设为静态,这样既可以不用this指针了。

// 类定义
// AStar.hpp
class GeneratorAdapter
	{
	private:
		Generator *t;
	public:
		GeneratorAdapter(Generator *t_) :t(t_) {}
		CoordinateList operator()(Vec2i source_, Vec2i target_, Vec2i upper_left_, Vec2i lower_right_, int alpha);
	};

// 类实现
// AStar.cpp
AStar::CoordinateList AStar::GeneratorAdapter::operator()(Vec2i source_, Vec2i target_, Vec2i upper_left_, Vec2i lower_right_, int alpha)
{
	return t->findPath(source_, target_, upper_left_, lower_right_, alpha);
}

// 类引用
// main.cpp
AStar::GeneratorAdapter ad(&generator);
pool.enqueue(ad, start, end[i], upper_left, lower_right, alpha)

使用上述方法可以实现多线程的使用。

4. 结果输出

使用多线程的最终目的是并行实现多个函数,函数必定有输出。需要将并行的结果输出出来。

使用本方法的弊端是将子线程与主函数的父线程分离开,即申请完子线程之后父线程(主函数)继续运行。父线程运行结束后子线程不会销毁,直到子线程运行结束才会销毁。所以需要在父线程加入等待子线程结束才能继续运行的代码。

通过阅读ThreadPool.h可以看出,pool.enqueue的返回值是一个std::future,std::future需要使用get()方法去除其中的数据。所以实现思路是:申请完线程后,遍历所有线程,使用get将结果取出。

// main.cpp
std::vector<std::future<AStar::CoordinateList>> path;
	for (int i = 0; i < end.size(); ++i) {
		path.push_back(pool.enqueue(ad, start, end[i], upper_left, lower_right, alpha));
	}
	for (int i = 0; i < end.size(); ++i) {
		auto a = path[i].get();
	}

将pool的返回值引入vector中,申请完线程后使用get()方法等待线程运行结束。全部线程运行结束后在执行主函数的后续程序。

5. 参考

线程中常用的锁,有哪几种

C++多线程编程:基于现代C++的多线程库

C++11之std::future对象使用说明

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值