CmWorkQueue.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. #pragma once
  2. #include "CmPrerequisitesUtil.h"
  3. #include "boost/any.hpp"
  4. namespace CamelotFramework
  5. {
  6. /** \addtogroup Core
  7. * @{
  8. */
  9. /** \addtogroup General
  10. * @{
  11. */
  12. /** Interface to a general purpose request / response style background work queue.
  13. @remarks
  14. A work queue is a simple structure, where requests for work are placed
  15. onto the queue, then removed by a worker for processing, then finally
  16. a response is placed on the result queue for the originator to pick up
  17. at their leisure. The typical use for this is in a threaded environment,
  18. although any kind of deferred processing could use this approach to
  19. decouple and distribute work over a period of time even
  20. if it was single threaded.
  21. @par
  22. WorkQueues also incorporate thread pools. One or more background worker threads
  23. can wait on the queue and be notified when a request is waiting to be
  24. processed. For maximal thread usage, a WorkQueue instance should be shared
  25. among many sources of work, rather than many work queues being created.
  26. This way, you can share a small number of hardware threads among a large
  27. number of background tasks. This doesn't mean you have to implement all the
  28. request processing in one class, you can plug in many handlers in order to
  29. process the requests.
  30. */
  31. class CM_UTILITY_EXPORT WorkQueue
  32. {
  33. protected:
  34. typedef Map<String, UINT16>::type ChannelMap;
  35. ChannelMap mChannelMap;
  36. UINT16 mNextChannel;
  37. CM_MUTEX(mChannelMapMutex)
  38. public:
  39. /// Numeric identifier for a request
  40. typedef unsigned long long int RequestID;
  41. /** General purpose request structure.
  42. */
  43. class CM_UTILITY_EXPORT Request
  44. {
  45. friend class WorkQueue;
  46. protected:
  47. /// The request channel, as an integer
  48. UINT16 mChannel;
  49. /// The details of the request (user defined)
  50. boost::any mData;
  51. /// Retry count - set this to non-zero to have the request try again on failure
  52. UINT8 mRetryCount;
  53. /// Identifier (assigned by the system)
  54. RequestID mID;
  55. /// Abort Flag
  56. mutable bool mAborted;
  57. public:
  58. /// Constructor
  59. Request(UINT16 channel, const boost::any& rData, UINT8 retry, RequestID rid);
  60. ~Request();
  61. /// Set the abort flag
  62. void abortRequest() const { mAborted = true; }
  63. /// Get the request channel (top level categorisation)
  64. UINT16 getChannel() const { return mChannel; }
  65. /// Get the user details of this request
  66. const boost::any& getData() const { return mData; }
  67. /// Get the remaining retry count
  68. UINT8 getRetryCount() const { return mRetryCount; }
  69. /// Get the identifier of this request
  70. RequestID getID() const { return mID; }
  71. /// Get the abort flag
  72. bool getAborted() const { return mAborted; }
  73. };
  74. /** General purpose response structure.
  75. */
  76. struct CM_UTILITY_EXPORT Response
  77. {
  78. /// Pointer to the request that this response is in relation to
  79. Request* mRequest;
  80. /// Whether the work item succeeded or not
  81. bool mSuccess;
  82. /// Data associated with the result of the process
  83. boost::any mData;
  84. public:
  85. Response(Request* rq, bool success, const boost::any& data);
  86. ~Response();
  87. /// Get the request that this is a response to (NB destruction destroys this)
  88. const Request* getRequest() const { return mRequest; }
  89. /// Return whether this is a successful response
  90. bool succeeded() const { return mSuccess; }
  91. /// Return the response data (user defined, only valid on success)
  92. const boost::any& getData() const { return mData; }
  93. /// Abort the request
  94. void abortRequest() { mRequest->abortRequest(); }
  95. };
  96. /** Interface definition for a handler of requests.
  97. @remarks
  98. User classes are expected to implement this interface in order to
  99. process requests on the queue. It's important to realise that
  100. the calls to this class may be in a separate thread to the main
  101. render context, and as such it may not be possible to make
  102. rendersystem or other GPU-dependent calls in this handler. You can only
  103. do so if the queue was created with 'workersCanAccessRenderSystem'
  104. set to true, and OGRE_THREAD_SUPPORT=1, but this puts extra strain
  105. on the thread safety of the render system and is not recommended.
  106. It is best to perform CPU-side work in these handlers and let the
  107. response handler transfer results to the GPU in the main render thread.
  108. */
  109. class CM_UTILITY_EXPORT RequestHandler
  110. {
  111. public:
  112. RequestHandler() {}
  113. virtual ~RequestHandler() {}
  114. /** Return whether this handler can process a given request.
  115. @remarks
  116. Defaults to true, but if you wish to add several handlers each of
  117. which deal with different types of request, you can override
  118. this method.
  119. */
  120. virtual bool canHandleRequest(const Request* req, const WorkQueue* srcQ)
  121. { (void)srcQ; return !req->getAborted(); }
  122. /** The handler method every subclass must implement.
  123. If a failure is encountered, return a Response with a failure
  124. result rather than raise an exception.
  125. @param req The Request structure, which is effectively owned by the
  126. handler during this call. It must be attached to the returned
  127. Response regardless of success or failure.
  128. @param srcQ The work queue that this request originated from
  129. @return Pointer to a Response object - the caller is responsible
  130. for deleting the object.
  131. */
  132. virtual Response* handleRequest(Request* req, const WorkQueue* srcQ) = 0;
  133. };
  134. /** Interface definition for a handler of responses.
  135. @remarks
  136. User classes are expected to implement this interface in order to
  137. process responses from the queue. All calls to this class will be
  138. in the main render thread and thus all GPU resources will be
  139. available.
  140. */
  141. class CM_UTILITY_EXPORT ResponseHandler
  142. {
  143. public:
  144. ResponseHandler() {}
  145. virtual ~ResponseHandler() {}
  146. /** Return whether this handler can process a given response.
  147. @remarks
  148. Defaults to true, but if you wish to add several handlers each of
  149. which deal with different types of response, you can override
  150. this method.
  151. */
  152. virtual bool canHandleResponse(const Response* res, const WorkQueue* srcQ)
  153. { (void)srcQ; return !res->getRequest()->getAborted(); }
  154. /** The handler method every subclass must implement.
  155. @param res The Response structure. The caller is responsible for
  156. deleting this after the call is made, none of the data contained
  157. (except pointers to structures in user Any data) will persist
  158. after this call is returned.
  159. @param srcQ The work queue that this request originated from
  160. */
  161. virtual void handleResponse(const Response* res, const WorkQueue* srcQ) = 0;
  162. };
  163. protected:
  164. size_t mWorkerThreadCount;
  165. bool mIsRunning;
  166. unsigned long mResposeTimeLimitMS;
  167. typedef Deque<Request*>::type RequestQueue;
  168. RequestQueue mRequestQueue;
  169. RequestQueue mProcessQueue;
  170. /// Thread function
  171. struct WorkerFunc CM_THREAD_WORKER_INHERIT
  172. {
  173. WorkQueue* mQueue;
  174. WorkerFunc(WorkQueue* q)
  175. : mQueue(q) {}
  176. void operator()();
  177. void run();
  178. };
  179. WorkerFunc* mWorkerFunc;
  180. /** Intermediate structure to hold a pointer to a request handler which
  181. provides insurance against the handler itself being disconnected
  182. while the list remains unchanged.
  183. */
  184. class CM_UTILITY_EXPORT RequestHandlerHolder
  185. {
  186. protected:
  187. CM_RW_MUTEX(mRWMutex);
  188. RequestHandler* mHandler;
  189. public:
  190. RequestHandlerHolder(RequestHandler* handler)
  191. : mHandler(handler) {}
  192. // Disconnect the handler to allow it to be destroyed
  193. void disconnectHandler()
  194. {
  195. // write lock - must wait for all requests to finish
  196. CM_LOCK_RW_MUTEX_WRITE(mRWMutex);
  197. mHandler = 0;
  198. }
  199. /** Get handler pointer - note, only use this for == comparison or similar,
  200. do not attempt to call it as it is not thread safe.
  201. */
  202. RequestHandler* getHandler() { return mHandler; }
  203. /** Process a request if possible.
  204. @return Valid response if processed, null otherwise
  205. */
  206. Response* handleRequest(Request* req, const WorkQueue* srcQ)
  207. {
  208. // Read mutex so that multiple requests can be processed by the
  209. // same handler in parallel if required
  210. CM_LOCK_RW_MUTEX_READ(mRWMutex);
  211. Response* response = 0;
  212. if (mHandler)
  213. {
  214. if (mHandler->canHandleRequest(req, srcQ))
  215. {
  216. response = mHandler->handleRequest(req, srcQ);
  217. }
  218. }
  219. return response;
  220. }
  221. };
  222. // Hold these by shared pointer so they can be copied keeping same instance
  223. typedef std::shared_ptr<RequestHandlerHolder> RequestHandlerHolderPtr;
  224. typedef List<RequestHandlerHolderPtr>::type RequestHandlerList;
  225. typedef List<ResponseHandler*>::type ResponseHandlerList;
  226. typedef Map<UINT16, RequestHandlerList>::type RequestHandlerListByChannel;
  227. typedef Map<UINT16, ResponseHandlerList>::type ResponseHandlerListByChannel;
  228. RequestHandlerListByChannel mRequestHandlers;
  229. ResponseHandlerListByChannel mResponseHandlers;
  230. RequestID mRequestCount;
  231. bool mPaused;
  232. bool mAcceptRequests;
  233. bool mShuttingDown;
  234. /// Synchroniser token to wait / notify on thread init
  235. CM_THREAD_SYNCHRONISER(mInitSync)
  236. CM_THREAD_SYNCHRONISER(mRequestCondition)
  237. /// Init notification mutex (must lock before waiting on initCondition)
  238. CM_MUTEX(mInitMutex)
  239. CM_MUTEX(mRequestMutex)
  240. CM_MUTEX(mProcessMutex)
  241. CM_RW_MUTEX(mRequestHandlerMutex);
  242. #if CM_THREAD_SUPPORT
  243. typedef Vector<CM_THREAD_TYPE*>::type WorkerThreadList;
  244. WorkerThreadList mWorkers;
  245. #endif
  246. public:
  247. WorkQueue();
  248. ~WorkQueue();
  249. /** Start up the queue with the options that have been set.
  250. @param forceRestart If the queue is already running, whether to shut it
  251. down and restart.
  252. */
  253. void startup(bool forceRestart = true);
  254. /** Shut down the queue.
  255. */
  256. void shutdown();
  257. /** Add a request handler instance to the queue.
  258. @remarks
  259. Every queue must have at least one request handler instance for each
  260. channel in which requests are raised. If you
  261. add more than one handler per channel, then you must implement canHandleRequest
  262. differently in each if you wish them to respond to different requests.
  263. @param channel The channel for requests you want to handle
  264. @param rh Your handler
  265. */
  266. void addRequestHandler(UINT16 channel, RequestHandler* rh);
  267. /** Remove a request handler. */
  268. void removeRequestHandler(UINT16 channel, RequestHandler* rh);
  269. /** Add a response handler instance to the queue.
  270. @remarks
  271. Every queue must have at least one response handler instance for each
  272. channel in which requests are raised. If you add more than one, then you
  273. must implement canHandleResponse differently in each if you wish them
  274. to respond to different responses.
  275. @param channel The channel for responses you want to handle
  276. @param rh Your handler
  277. */
  278. void addResponseHandler(UINT16 channel, ResponseHandler* rh);
  279. /** Remove a Response handler. */
  280. void removeResponseHandler(UINT16 channel, ResponseHandler* rh);
  281. /**
  282. * @brief Gets the next free request identifier.
  283. *
  284. * @return The next free request identifier.
  285. */
  286. RequestID peekNextFreeRequestId();
  287. /** Add a new request to the queue.
  288. @param channel The channel this request will go into = 0; the channel is the top-level
  289. categorisation of the request
  290. @param requestType An identifier that's unique within this queue which
  291. identifies the type of the request (user decides the actual value)
  292. @param rData The data required by the request process.
  293. @param retryCount The number of times the request should be retried
  294. if it fails.
  295. @param forceSynchronous Forces the request to be processed immediately
  296. even if threading is enabled.
  297. @returns The ID of the request that has been added
  298. */
  299. RequestID addRequest(UINT16 channel, const boost::any& rData, UINT8 retryCount = 0,
  300. bool forceSynchronous = false);
  301. /// Put a Request on the queue with a specific RequestID.
  302. void addRequestWithRID(RequestID rid, UINT16 channel, const boost::any& rData, UINT8 retryCount);
  303. /** Abort a previously issued request.
  304. If the request is still waiting to be processed, it will be
  305. removed from the queue.
  306. @param id The ID of the previously issued request.
  307. */
  308. void abortRequest(RequestID id);
  309. /** Abort all previously issued requests in a given channel.
  310. Any requests still waiting to be processed of the given channel, will be
  311. removed from the queue.
  312. @param channel The type of request to be aborted
  313. */
  314. void abortRequestsByChannel(UINT16 channel);
  315. /** Abort all previously issued requests.
  316. Any requests still waiting to be processed will be removed from the queue.
  317. Any requests that are being processed will still complete.
  318. */
  319. void abortAllRequests();
  320. /** Set whether to pause further processing of any requests.
  321. If true, any further requests will simply be queued and not processed until
  322. setPaused(false) is called. Any requests which are in the process of being
  323. worked on already will still continue.
  324. */
  325. void setPaused(bool pause);
  326. /// Return whether the queue is paused ie not sending more work to workers
  327. bool isPaused() const;
  328. /** Set whether to accept new requests or not.
  329. If true, requests are added to the queue as usual. If false, requests
  330. are silently ignored until setRequestsAccepted(true) is called.
  331. */
  332. void setRequestsAccepted(bool accept);
  333. /// Returns whether requests are being accepted right now
  334. bool getRequestsAccepted() const;
  335. /** Get the number of worker threads that this queue will start when
  336. startup() is called.
  337. */
  338. size_t getWorkerThreadCount() const;
  339. /** Set the number of worker threads that this queue will start
  340. when startup() is called (default 1).
  341. Calling this will have no effect unless the queue is shut down and
  342. restarted.
  343. */
  344. void setWorkerThreadCount(size_t c);
  345. /** Get a channel ID for a given channel name.
  346. @remarks
  347. Channels are assigned on a first-come, first-served basis and are
  348. not persistent across application instances. This method allows
  349. applications to not worry about channel clashes through manually
  350. assigned channel numbers.
  351. */
  352. UINT16 getChannel(const String& channelName);
  353. /** Returns whether the queue is trying to shut down. */
  354. bool isShuttingDown() const { return mShuttingDown; }
  355. protected:
  356. void processRequestResponse(Request* r);
  357. Response* processRequest(Request* r);
  358. void processResponse(Response* r);
  359. /** To be called by a separate thread; will return immediately if there
  360. are items in the queue, or suspend the thread until new items are added
  361. otherwise.
  362. */
  363. void waitForNextRequest();
  364. /** Process the next request on the queue.
  365. @remarks
  366. This method is public, but only intended for advanced users to call.
  367. The only reason you would call this, is if you were using your
  368. own thread to drive the worker processing. The thread calling this
  369. method will be the thread used to call the RequestHandler.
  370. */
  371. void processNextRequest();
  372. /// Main function for each thread spawned.
  373. void threadMain();
  374. /// Notify workers about a new request.
  375. void notifyWorkers();
  376. };
  377. }