69 lines
1.5 KiB
C++
69 lines
1.5 KiB
C++
#ifndef CCTHREADPOOL_H
|
|
#define CCTHREADPOOL_H
|
|
|
|
#include <thread>
|
|
#include <functional>
|
|
#include <queue>
|
|
#include <mutex>
|
|
#include <vector>
|
|
#include <map>
|
|
#include "CCThread.h"
|
|
|
|
|
|
|
|
class CCThreadPool
|
|
{
|
|
public:
|
|
struct TaskPool {
|
|
std::thread* thread;
|
|
bool Running = false;
|
|
};
|
|
|
|
public:
|
|
CCThreadPool() = default;
|
|
explicit CCThreadPool(int numThreads);
|
|
void InitStart(int numThreads);
|
|
template<typename Func,typename... Args>
|
|
void AddTask(Func && func, Args&&... args);
|
|
unsigned int GetThreadCount() const;
|
|
unsigned int GetUnusedCount();
|
|
void SetThreadTimeout(unsigned int us);
|
|
std::vector<int> GetThreadUnusedID();
|
|
void Stop();
|
|
|
|
|
|
private:
|
|
void worker(int ID);
|
|
std::vector<TaskPool*> m_thread;
|
|
TaskPool* T;
|
|
std::vector<std::function<void()>> m_taskQueue;
|
|
std::mutex m_mutex;
|
|
bool m_running;
|
|
unsigned int m_threadCount, m_thread_Time = 1000 * 1000;
|
|
|
|
|
|
};
|
|
template<typename Func,typename... Args>
|
|
inline void CCThreadPool::AddTask(Func && func, Args&&... args) {
|
|
m_mutex.lock();
|
|
std::function<void()> FUNS = std::bind(std::forward<Func>(func), std::forward<Args>(args)...);
|
|
if(FUNS)
|
|
{
|
|
for (int i = 0;i < m_threadCount;i++)
|
|
{
|
|
if(!m_thread[i]->Running)
|
|
{
|
|
m_taskQueue[i] = FUNS;
|
|
m_thread[i]->Running = true;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
//Threading::Sleep(1000 * 16);
|
|
m_mutex.unlock();
|
|
}
|
|
|
|
|
|
|
|
#endif //CCTHREADPOOL_H
|