WebSocket_CPP_98/CC_SDK_VS/CCThreadPool.h
2025-12-29 09:55:17 +08:00

42 lines
1.1 KiB
C++
Executable File

#pragma once
#include "CCThread.h"
#include "CCMutex.h"
#include "vector"
#include "queue"
#include "iostream"
#include <functional> // Ìí¼Ó´ËÐÐ
namespace CTL {
class ThreadPool
{
using Fun_Type = std::function<void()>; // ÐèҪȷ±£std::function¿ÉÓÃ
struct TaskBase
{
int ID = -1;
bool IsRunning = false;
Thread* thread_t = nullptr;
};
public:
ThreadPool();
~ThreadPool();
bool InitStart(int Core);
void Stop();
template<typename FUN, typename... ARGS>
void AddTask(FUN&& fun, ARGS&& ...Args);
private:
std::queue<Fun_Type> m_TaskQueue{};
std::vector<TaskBase*> m_Threads{};
CTL::Mutex m_Mutex;
bool isRunning = true;
int M_Core = 10;
void Worker(int ID);
};
template<typename FUN, typename ...ARGS>
inline void ThreadPool::AddTask(FUN&& fun, ARGS&& ...Args)
{
CTL::AutoLock lock(m_Mutex);
auto task = std::bind(std::forward<FUN>(fun), std::forward<ARGS>(Args)...);
m_TaskQueue.push(task);
}
}