Cornell Cocos
Cornell Extensions to Cocos2d
All Classes Functions Variables Enumerations Enumerator Friends
CUThreadPool.h
1 //
2 // CUThreadPool.h
3 // Cornell Extensions to Cocos2D
4 //
5 // Module for a pool of threads capable of executing asynchronous tasks. Each task
6 // is specified by a void function. There are no guarantees about thread safety;
7 // that is responsibility of the author of each task.
8 //
9 // This code is largely taken from the Cocos2d file AudioEngine.cpp, from the code
10 // for asynchronous asset loading. There was no need to couple this tool with that
11 // class, so we have pulled it out (with some notable safety changes) into a general
12 // purpose tool.
13 //
14 // Author: Walker White
15 // Version: 12/3/15
16 //
17 #ifndef __CU_THREAD_POOL_H__
18 #define __CU_THREAD_POOL_H__
19 
20 #include <stdio.h>
21 #include <condition_variable>
22 #include <queue>
23 #include <vector>
24 #include <cocos2d.h>
25 
26 NS_CC_BEGIN
27 
28 #pragma mark -
29 #pragma mark Thread Pool
30 
51 class CC_DLL ThreadPool : public Ref {
52 private:
54  CC_DISALLOW_COPY_AND_ASSIGN(ThreadPool);
55 
56 protected:
58  std::vector<std::thread> _workers;
60  std::queue< std::function<void()> > _taskQueue;
61 
63  std::mutex _queueMutex;
65  std::condition_variable _taskCondition;
66 
68  bool _detach;
70  bool _stop;
72  int _complete;
73 
75  void threadFunc();
76 
77 
78 public:
79 #pragma mark Static Constructors
80 
91  static ThreadPool* create(int threads = 4);
92 
93 
94 #pragma mark Task Management
95 
104  void addTask(const std::function<void()> &task);
105 
113  void stop();
114 
124  bool isStopped() const { return _stop; }
125 
133  bool isShutdown() const { return _workers.size() == _complete; }
134 
135 
136 #pragma mark -
137 #pragma mark Initializers
138 CC_CONSTRUCTOR_ACCESS:
142  ThreadPool();
143 
151  ~ThreadPool();
152 
164  virtual bool init(int threads = 4);
165 
166 };
167 
168 NS_CC_END
169 #endif /* defined(__CU_THREAD_POOL_H__) */
170 
171 
172 
std::vector< std::thread > _workers
Definition: CUThreadPool.h:58
bool isStopped() const
Definition: CUThreadPool.h:124
bool isShutdown() const
Definition: CUThreadPool.h:133
int _complete
Definition: CUThreadPool.h:72
bool _detach
Definition: CUThreadPool.h:68
bool _stop
Definition: CUThreadPool.h:70
std::condition_variable _taskCondition
Definition: CUThreadPool.h:65
std::queue< std::function< void()> > _taskQueue
Definition: CUThreadPool.h:60
Definition: CUThreadPool.h:51
std::mutex _queueMutex
Definition: CUThreadPool.h:63