threadpool.h 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #ifndef THREAD_POOL_H
  2. #define THREAD_POOL_H
  3. #include <condition_variable>
  4. #include <functional>
  5. #include <memory>
  6. #include <mutex>
  7. #include <thread>
  8. class ThreadPool
  9. {
  10. public:
  11. static bool init(int threadsNum = 6, int tasksNum = 10);
  12. static bool addTask(std::function<void(std::shared_ptr<void>)> func, std::shared_ptr<void> par);
  13. static void releasePool();
  14. private:
  15. typedef struct Task
  16. {
  17. //任务函数
  18. std::function<void(std::shared_ptr<void>)> func;
  19. //任务函数参数
  20. std::shared_ptr<void> par;
  21. } Task;
  22. typedef struct Threads
  23. {
  24. std::thread::id id;
  25. bool isTerminate;
  26. bool isWorking;
  27. } Threads;
  28. static void threadEventLoop(void* arg);
  29. static int m_maxThreads;
  30. static int m_freeThreads;
  31. static int m_maxTasks;
  32. static int m_pushIndex;
  33. static int m_readIndex;
  34. static int m_size;
  35. //初始化标志,保证init首次调用有效
  36. static int m_initFlag;
  37. static std::vector<Threads> m_threadsQueue;
  38. static std::mutex m_mutex;
  39. static std::condition_variable m_cond;
  40. static std::vector<Task> m_tasksQueue;
  41. };
  42. #endif