CmWorkQueue.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. /*
  2. -----------------------------------------------------------------------------
  3. This source file is part of OGRE
  4. (Object-oriented Graphics Rendering Engine)
  5. For the latest info, see http://www.ogre3d.org/
  6. Copyright (c) 2000-2011 Torus Knot Software Ltd
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13. The above copyright notice and this permission notice shall be included in
  14. all copies or substantial portions of the Software.
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. THE SOFTWARE.
  22. -----------------------------------------------------------------------------
  23. */
  24. #include "CmWorkQueue.h"
  25. #include "CmDebug.h"
  26. namespace CamelotFramework {
  27. WorkQueue::WorkQueue()
  28. : mNextChannel(0)
  29. , mWorkerThreadCount(1)
  30. , mIsRunning(false)
  31. , mWorkerFunc(0)
  32. , mRequestCount(0)
  33. , mPaused(false)
  34. , mAcceptRequests(true)
  35. {}
  36. //---------------------------------------------------------------------
  37. WorkQueue::~WorkQueue()
  38. {
  39. shutdown();
  40. for (RequestQueue::iterator i = mRequestQueue.begin(); i != mRequestQueue.end(); ++i)
  41. {
  42. CM_DELETE(*i, Request, ScratchAlloc);
  43. }
  44. mRequestQueue.clear();
  45. }
  46. //---------------------------------------------------------------------
  47. void WorkQueue::startup(bool forceRestart)
  48. {
  49. if (mIsRunning)
  50. {
  51. if (forceRestart)
  52. shutdown();
  53. else
  54. return;
  55. }
  56. mShuttingDown = false;
  57. mWorkerFunc = cm_new<WorkerFunc>(this);
  58. #if CM_THREAD_SUPPORT
  59. for (UINT8 i = 0; i < mWorkerThreadCount; ++i)
  60. {
  61. CM_THREAD_CREATE(t, *mWorkerFunc);
  62. mWorkers.push_back(t);
  63. }
  64. #endif
  65. mIsRunning = true;
  66. }
  67. //---------------------------------------------------------------------
  68. void WorkQueue::shutdown()
  69. {
  70. if( !mIsRunning )
  71. return;
  72. mShuttingDown = true;
  73. abortAllRequests();
  74. #if CM_THREAD_SUPPORT
  75. // wake all threads (they should check shutting down as first thing after wait)
  76. CM_THREAD_NOTIFY_ALL(mRequestCondition)
  77. // all our threads should have been woken now, so join
  78. for (WorkerThreadList::iterator i = mWorkers.begin(); i != mWorkers.end(); ++i)
  79. {
  80. (*i)->join();
  81. CM_THREAD_DESTROY(*i);
  82. }
  83. mWorkers.clear();
  84. #endif
  85. if (mWorkerFunc != nullptr)
  86. {
  87. cm_delete(mWorkerFunc);
  88. mWorkerFunc = nullptr;
  89. }
  90. mIsRunning = false;
  91. }
  92. //---------------------------------------------------------------------
  93. void WorkQueue::addRequestHandler(UINT16 channel, RequestHandler* rh)
  94. {
  95. CM_LOCK_RW_MUTEX_WRITE(mRequestHandlerMutex);
  96. RequestHandlerListByChannel::iterator i = mRequestHandlers.find(channel);
  97. if (i == mRequestHandlers.end())
  98. i = mRequestHandlers.insert(RequestHandlerListByChannel::value_type(channel, RequestHandlerList())).first;
  99. RequestHandlerList& handlers = i->second;
  100. bool duplicate = false;
  101. for (RequestHandlerList::iterator j = handlers.begin(); j != handlers.end(); ++j)
  102. {
  103. if ((*j)->getHandler() == rh)
  104. {
  105. duplicate = true;
  106. break;
  107. }
  108. }
  109. if (!duplicate)
  110. handlers.push_back(cm_shared_ptr<RequestHandlerHolder>(rh));
  111. }
  112. //---------------------------------------------------------------------
  113. void WorkQueue::removeRequestHandler(UINT16 channel, RequestHandler* rh)
  114. {
  115. CM_LOCK_RW_MUTEX_WRITE(mRequestHandlerMutex);
  116. RequestHandlerListByChannel::iterator i = mRequestHandlers.find(channel);
  117. if (i != mRequestHandlers.end())
  118. {
  119. RequestHandlerList& handlers = i->second;
  120. for (RequestHandlerList::iterator j = handlers.begin(); j != handlers.end(); ++j)
  121. {
  122. if ((*j)->getHandler() == rh)
  123. {
  124. // Disconnect - this will make it safe across copies of the list
  125. // this is threadsafe and will wait for existing processes to finish
  126. (*j)->disconnectHandler();
  127. handlers.erase(j);
  128. break;
  129. }
  130. }
  131. }
  132. }
  133. //---------------------------------------------------------------------
  134. void WorkQueue::addResponseHandler(UINT16 channel, ResponseHandler* rh)
  135. {
  136. ResponseHandlerListByChannel::iterator i = mResponseHandlers.find(channel);
  137. if (i == mResponseHandlers.end())
  138. i = mResponseHandlers.insert(ResponseHandlerListByChannel::value_type(channel, ResponseHandlerList())).first;
  139. ResponseHandlerList& handlers = i->second;
  140. if (std::find(handlers.begin(), handlers.end(), rh) == handlers.end())
  141. handlers.push_back(rh);
  142. }
  143. //---------------------------------------------------------------------
  144. void WorkQueue::removeResponseHandler(UINT16 channel, ResponseHandler* rh)
  145. {
  146. ResponseHandlerListByChannel::iterator i = mResponseHandlers.find(channel);
  147. if (i != mResponseHandlers.end())
  148. {
  149. ResponseHandlerList& handlers = i->second;
  150. ResponseHandlerList::iterator j = std::find(
  151. handlers.begin(), handlers.end(), rh);
  152. if (j != handlers.end())
  153. handlers.erase(j);
  154. }
  155. }
  156. //---------------------------------------------------------------------
  157. WorkQueue::RequestID WorkQueue::peekNextFreeRequestId()
  158. {
  159. {
  160. // lock to acquire rid and push request to the queue
  161. CM_LOCK_MUTEX(mRequestMutex)
  162. RequestID rid = mRequestCount + 1;
  163. return rid;
  164. }
  165. }
  166. //---------------------------------------------------------------------
  167. WorkQueue::RequestID WorkQueue::addRequest(UINT16 channel,
  168. const boost::any& rData, UINT8 retryCount, bool forceSynchronous)
  169. {
  170. Request* req = 0;
  171. RequestID rid = 0;
  172. {
  173. // lock to acquire rid and push request to the queue
  174. CM_LOCK_MUTEX(mRequestMutex)
  175. if (!mAcceptRequests || mShuttingDown)
  176. return 0;
  177. rid = ++mRequestCount;
  178. req = cm_new<Request, ScratchAlloc>(channel, rData, retryCount, rid);
  179. #if CM_THREAD_SUPPORT
  180. if (!forceSynchronous)
  181. {
  182. mRequestQueue.push_back(req);
  183. notifyWorkers();
  184. return rid;
  185. }
  186. #endif
  187. }
  188. processRequestResponse(req);
  189. return rid;
  190. }
  191. //---------------------------------------------------------------------
  192. void WorkQueue::addRequestWithRID(WorkQueue::RequestID rid, UINT16 channel,
  193. const boost::any& rData, UINT8 retryCount)
  194. {
  195. // lock to push request to the queue
  196. CM_LOCK_MUTEX(mRequestMutex)
  197. if (mShuttingDown)
  198. return;
  199. Request* req = cm_new<Request, ScratchAlloc>(channel, rData, retryCount, rid);
  200. #if CM_THREAD_SUPPORT
  201. mRequestQueue.push_back(req);
  202. notifyWorkers();
  203. #else
  204. processRequestResponse(req);
  205. #endif
  206. }
  207. //---------------------------------------------------------------------
  208. void WorkQueue::abortRequest(RequestID id)
  209. {
  210. CM_LOCK_MUTEX(mProcessMutex)
  211. // NOTE: Pending requests are exist any of RequestQueue, ProcessQueue and
  212. // ResponseQueue when keeping ProcessMutex, so we check all of these queues.
  213. for (RequestQueue::iterator i = mProcessQueue.begin(); i != mProcessQueue.end(); ++i)
  214. {
  215. if ((*i)->getID() == id)
  216. {
  217. (*i)->abortRequest();
  218. break;
  219. }
  220. }
  221. {
  222. CM_LOCK_MUTEX(mRequestMutex)
  223. for (RequestQueue::iterator i = mRequestQueue.begin(); i != mRequestQueue.end(); ++i)
  224. {
  225. if ((*i)->getID() == id)
  226. {
  227. (*i)->abortRequest();
  228. break;
  229. }
  230. }
  231. }
  232. }
  233. //---------------------------------------------------------------------
  234. void WorkQueue::abortRequestsByChannel(UINT16 channel)
  235. {
  236. CM_LOCK_MUTEX(mProcessMutex)
  237. for (RequestQueue::iterator i = mProcessQueue.begin(); i != mProcessQueue.end(); ++i)
  238. {
  239. if ((*i)->getChannel() == channel)
  240. {
  241. (*i)->abortRequest();
  242. }
  243. }
  244. {
  245. CM_LOCK_MUTEX(mRequestMutex)
  246. for (RequestQueue::iterator i = mRequestQueue.begin(); i != mRequestQueue.end(); ++i)
  247. {
  248. if ((*i)->getChannel() == channel)
  249. {
  250. (*i)->abortRequest();
  251. }
  252. }
  253. }
  254. }
  255. //---------------------------------------------------------------------
  256. void WorkQueue::abortAllRequests()
  257. {
  258. CM_LOCK_MUTEX(mProcessMutex)
  259. for (RequestQueue::iterator i = mProcessQueue.begin(); i != mProcessQueue.end(); ++i)
  260. {
  261. (*i)->abortRequest();
  262. }
  263. {
  264. CM_LOCK_MUTEX(mRequestMutex)
  265. for (RequestQueue::iterator i = mRequestQueue.begin(); i != mRequestQueue.end(); ++i)
  266. {
  267. (*i)->abortRequest();
  268. }
  269. }
  270. }
  271. //---------------------------------------------------------------------
  272. void WorkQueue::setPaused(bool pause)
  273. {
  274. CM_LOCK_MUTEX(mRequestMutex)
  275. mPaused = pause;
  276. }
  277. //---------------------------------------------------------------------
  278. bool WorkQueue::isPaused() const
  279. {
  280. return mPaused;
  281. }
  282. //---------------------------------------------------------------------
  283. void WorkQueue::setRequestsAccepted(bool accept)
  284. {
  285. CM_LOCK_MUTEX(mRequestMutex)
  286. mAcceptRequests = accept;
  287. }
  288. //---------------------------------------------------------------------
  289. bool WorkQueue::getRequestsAccepted() const
  290. {
  291. return mAcceptRequests;
  292. }
  293. //---------------------------------------------------------------------
  294. size_t WorkQueue::getWorkerThreadCount() const
  295. {
  296. return mWorkerThreadCount;
  297. }
  298. //---------------------------------------------------------------------
  299. void WorkQueue::setWorkerThreadCount(size_t c)
  300. {
  301. mWorkerThreadCount = c;
  302. }
  303. //---------------------------------------------------------------------
  304. UINT16 WorkQueue::getChannel(const String& channelName)
  305. {
  306. CM_LOCK_MUTEX(mChannelMapMutex)
  307. ChannelMap::iterator i = mChannelMap.find(channelName);
  308. if (i == mChannelMap.end())
  309. {
  310. i = mChannelMap.insert(ChannelMap::value_type(channelName, mNextChannel++)).first;
  311. }
  312. return i->second;
  313. }
  314. //---------------------------------------------------------------------
  315. void WorkQueue::processRequestResponse(Request* r)
  316. {
  317. Response* response = processRequest(r);
  318. CM_LOCK_MUTEX(mProcessMutex)
  319. RequestQueue::iterator it;
  320. for( it = mProcessQueue.begin(); it != mProcessQueue.end(); ++it )
  321. {
  322. if( (*it) == r )
  323. {
  324. mProcessQueue.erase( it );
  325. break;
  326. }
  327. }
  328. if (response)
  329. {
  330. if (!response->succeeded())
  331. {
  332. // Failed, should we retry?
  333. const Request* req = response->getRequest();
  334. if (req->getRetryCount())
  335. {
  336. addRequestWithRID(req->getID(), req->getChannel(), req->getData(),
  337. req->getRetryCount() - 1);
  338. // discard response (this also deletes request)
  339. CM_DELETE(response, Response, ScratchAlloc);
  340. return;
  341. }
  342. }
  343. processResponse(response);
  344. CM_DELETE(response, Response, ScratchAlloc);
  345. }
  346. else
  347. {
  348. // no response, delete request
  349. gDebug().logWarning("warning: no handler processed request "
  350. + toString(r->getID()) + ", channel " + toString(r->getChannel()));
  351. CM_DELETE(r, Request, ScratchAlloc);
  352. }
  353. }
  354. WorkQueue::Response* WorkQueue::processRequest(Request* r)
  355. {
  356. RequestHandlerListByChannel handlerListCopy;
  357. {
  358. // lock the list only to make a copy of it, to maximise parallelism
  359. CM_LOCK_RW_MUTEX_READ(mRequestHandlerMutex);
  360. handlerListCopy = mRequestHandlers;
  361. }
  362. Response* response = 0;
  363. RequestHandlerListByChannel::iterator i = handlerListCopy.find(r->getChannel());
  364. if (i != handlerListCopy.end())
  365. {
  366. RequestHandlerList& handlers = i->second;
  367. for (RequestHandlerList::reverse_iterator j = handlers.rbegin(); j != handlers.rend(); ++j)
  368. {
  369. // threadsafe call which tests canHandleRequest and calls it if so
  370. response = (*j)->handleRequest(r, this);
  371. if (response)
  372. break;
  373. }
  374. }
  375. return response;
  376. }
  377. //---------------------------------------------------------------------
  378. void WorkQueue::processResponse(Response* r)
  379. {
  380. ResponseHandlerListByChannel::iterator i = mResponseHandlers.find(r->getRequest()->getChannel());
  381. if (i != mResponseHandlers.end())
  382. {
  383. ResponseHandlerList& handlers = i->second;
  384. for (ResponseHandlerList::reverse_iterator j = handlers.rbegin(); j != handlers.rend(); ++j)
  385. {
  386. if ((*j)->canHandleResponse(r, this))
  387. {
  388. (*j)->handleResponse(r, this);
  389. }
  390. }
  391. }
  392. }
  393. //---------------------------------------------------------------------
  394. void WorkQueue::processNextRequest()
  395. {
  396. Request* request = 0;
  397. {
  398. // scoped to only lock while retrieving the next request
  399. CM_LOCK_MUTEX(mProcessMutex)
  400. {
  401. CM_LOCK_MUTEX(mRequestMutex)
  402. if (!mRequestQueue.empty())
  403. {
  404. request = mRequestQueue.front();
  405. mRequestQueue.pop_front();
  406. mProcessQueue.push_back( request );
  407. }
  408. }
  409. }
  410. if (request)
  411. {
  412. processRequestResponse(request);
  413. }
  414. }
  415. //---------------------------------------------------------------------
  416. void WorkQueue::waitForNextRequest()
  417. {
  418. #if CM_THREAD_SUPPORT
  419. // Lock; note that OGRE_THREAD_WAIT will free the lock
  420. CM_LOCK_MUTEX_NAMED(mRequestMutex, queueLock);
  421. if (mRequestQueue.empty())
  422. {
  423. // frees lock and suspends the thread
  424. CM_THREAD_WAIT(mRequestCondition, mRequestMutex, queueLock);
  425. }
  426. // When we get back here, it's because we've been notified
  427. // and thus the thread has been woken up. Lock has also been
  428. // re-acquired, but we won't use it. It's safe to try processing and fail
  429. // if another thread has got in first and grabbed the request
  430. #endif
  431. }
  432. //---------------------------------------------------------------------
  433. void WorkQueue::threadMain()
  434. {
  435. // default worker thread
  436. #if CM_THREAD_SUPPORT
  437. // Spin forever until we're told to shut down
  438. while (!isShuttingDown())
  439. {
  440. waitForNextRequest();
  441. processNextRequest();
  442. }
  443. #endif
  444. }
  445. //---------------------------------------------------------------------
  446. void WorkQueue::notifyWorkers()
  447. {
  448. // wake up waiting thread
  449. CM_THREAD_NOTIFY_ONE(mRequestCondition)
  450. }
  451. //---------------------------------------------------------------------
  452. WorkQueue::Request::Request(UINT16 channel, const boost::any& rData, UINT8 retry, RequestID rid)
  453. : mChannel(channel), mData(rData), mRetryCount(retry), mID(rid), mAborted(false)
  454. {
  455. }
  456. //---------------------------------------------------------------------
  457. WorkQueue::Request::~Request()
  458. {
  459. }
  460. //---------------------------------------------------------------------
  461. //---------------------------------------------------------------------
  462. WorkQueue::Response::Response(Request* rq, bool success, const boost::any& data)
  463. : mRequest(rq), mSuccess(success), mData(data)
  464. {
  465. }
  466. //---------------------------------------------------------------------
  467. WorkQueue::Response::~Response()
  468. {
  469. CM_DELETE(mRequest, Request, ScratchAlloc);
  470. }
  471. //---------------------------------------------------------------------
  472. void WorkQueue::WorkerFunc::operator()()
  473. {
  474. mQueue->threadMain();
  475. }
  476. void WorkQueue::WorkerFunc::run()
  477. {
  478. mQueue->threadMain();
  479. }
  480. }