异构线程池的c++实现方案

本文介绍了异构线程池的概念,其中线程与任务之间存在绑定关系,每个线程有特定功能。文章详细展示了TThreadPool和TThread两个类的设计,包括线程的添加、删除、任务的分配和处理,以及如何通过线程池向特定线程添加任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

概要

通常线程池是同质的,每个线程都可以执行任意的task(每个线程中的task顺序执行),如下图所示:

 但本文所介绍的线程和task之间有绑定关系,如A task只能跑在A thread上(因此称为异构线程池,每个线程的功能是有所区别的),如下图所示:

接口设计

TThreadPool接口设计

// 线程池
class TThreadPool
{
public:
    TThreadPool() {}
	TThreadPool(const TThreadPool&) = delete;
	TThreadPool& operator=(const TThreadPool& other) = delete;
    ~TThreadPool();
    bool add_thread(std::string name); // add one thread into pool
    bool delete_thread(std::string name); // remove one thread from pool
    TThread* get_thread_by_name(std::string threadname); // get the thread by name, don't delete return object by yourself
	bool append_task_by_thread(const std::string threadname, const std::function<void()>& task); // add task to pointed thread

private:
	std::mutex m_mutex;
	std::map<std::string, TThread*> m_threads;
};

 TThreadPool类的主要功能是管理创建的线程(TThread,它是线程的具体实现),它提供了增加/删除线程的接口,同时给每个线程打上了标签(name)。

TThread接口设计


                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值