概要
通常线程池是同质的,每个线程都可以执行任意的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)。