设计思路
算了,直接上代码,自己看吧。
/*******************************************************
* @FileName: Task.h
* @Author: xxxx
* @CreatedTime: Jul 17th 2020
* @Description:
* Wrapped thread pool task.
********************************************************/
#ifndef __TASK__H___ // macro name too short, so make it a little complicated.
#define __TASK__H___
#if defined _WIN32 || defined _WIN64
# ifndef WIN32
# define WIN32
# endif
#endif
// For corssplatform
#ifdef WIN32
#define TASKAPI __stdcall
#else
#define TASKAPI
#endif
#include <iostream>
typedef void* THPHANDLE;
#define THP_NULL_HANDLE (nullptr)
class Task
{
public:
virtual int run() = 0;
virtual ~Task() = default;
};
typedef int(*CBFct_t)(void*);
typedef void(*CBArgFree_t)(void*);
int TASKAPI THP_Intialize(THPHANDLE * ph, int sz);
int TASKAPI THP_Unitialize(THPHANDLE h);
int TASKAPI THP_PushTask(THPHANDLE h, Task* t);
int TASKAPI THP_PushTask(THPHANDLE h, CBFct_t cb, void* arg = nullptr, CBArgFree_t argfree = nullptr);
#endif // !__TASK__H___
/*******************************************************
* @FileName: ThreadPool.h
* @Author: xxxxx
* @CreatedTime: Jul 17th 2020
* @Description:
* Base thread pool tool.
********************************************************/
#ifndef __THREAD_POOL_H__
#define __THREAD_POOL_H__
#include "Task.h"
#include <thread>
#include <mutex>
#include <condition_variable>
#include <deque>
#include <atomic>
class CallbackTask : public Task
{
public:
typedef int(*CallbackFct)(void*);
typedef void(*CallbackTaskArgFree)(void*);
CallbackTask(CallbackFct cb, void* arg, CallbackTaskArgFree cbfree = nullptr);
virtual int run() override;
~CallbackTask();
private:
CallbackFct m_cb{
nullptr };
CallbackTaskArgFree m_cbFree{
nullptr };
void * m_arg{
nullptr };
};
class ThreadPool
{
public:
/* 构造函数 已被私有化,该类只能通过工厂方法,实现堆中动态对象的获取, delete this 的深层来源 */
/* 友元函数实现 创建 */
friend ThreadPool* alloc_pool();
friend void free_pool(ThreadPool* pool);
/* static public 成员方式 实现创建 */
static ThreadPool* create();
void destroy();
int init(int sz);
int fini();
int push(Task* p_task);
protected:
int pop(Task** pp_task);
bool is_empty();
private: