基于C++ std::thread 的线程池

设计思路

算了,直接上代码,自己看吧。

/*******************************************************
 * @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:
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值