2
0

CmWorkQueue.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  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(RequestHandlerHolderPtr(CM_NEW(RequestHandlerHolder, GenAlloc) RequestHandlerHolder(rh),
  111. &MemAllocDeleter<RequestHandlerHolder, GenAlloc>::deleter));
  112. }
  113. //---------------------------------------------------------------------
  114. void WorkQueue::removeRequestHandler(UINT16 channel, RequestHandler* rh)
  115. {
  116. CM_LOCK_RW_MUTEX_WRITE(mRequestHandlerMutex);
  117. RequestHandlerListByChannel::iterator i = mRequestHandlers.find(channel);
  118. if (i != mRequestHandlers.end())
  119. {
  120. RequestHandlerList& handlers = i->second;
  121. for (RequestHandlerList::iterator j = handlers.begin(); j != handlers.end(); ++j)
  122. {
  123. if ((*j)->getHandler() == rh)
  124. {
  125. // Disconnect - this will make it safe across copies of the list
  126. // this is threadsafe and will wait for existing processes to finish
  127. (*j)->disconnectHandler();
  128. handlers.erase(j);
  129. break;
  130. }
  131. }
  132. }
  133. }
  134. //---------------------------------------------------------------------
  135. void WorkQueue::addResponseHandler(UINT16 channel, ResponseHandler* rh)
  136. {
  137. ResponseHandlerListByChannel::iterator i = mResponseHandlers.find(channel);
  138. if (i == mResponseHandlers.end())
  139. i = mResponseHandlers.insert(ResponseHandlerListByChannel::value_type(channel, ResponseHandlerList())).first;
  140. ResponseHandlerList& handlers = i->second;
  141. if (std::find(handlers.begin(), handlers.end(), rh) == handlers.end())
  142. handlers.push_back(rh);
  143. }
  144. //---------------------------------------------------------------------
  145. void WorkQueue::removeResponseHandler(UINT16 channel, ResponseHandler* rh)
  146. {
  147. ResponseHandlerListByChannel::iterator i = mResponseHandlers.find(channel);
  148. if (i != mResponseHandlers.end())
  149. {
  150. ResponseHandlerList& handlers = i->second;
  151. ResponseHandlerList::iterator j = std::find(
  152. handlers.begin(), handlers.end(), rh);
  153. if (j != handlers.end())
  154. handlers.erase(j);
  155. }
  156. }
  157. //---------------------------------------------------------------------
  158. WorkQueue::RequestID WorkQueue::peekNextFreeRequestId()
  159. {
  160. {
  161. // lock to acquire rid and push request to the queue
  162. CM_LOCK_MUTEX(mRequestMutex)
  163. RequestID rid = mRequestCount + 1;
  164. return rid;
  165. }
  166. }
  167. //---------------------------------------------------------------------
  168. WorkQueue::RequestID WorkQueue::addRequest(UINT16 channel,
  169. const boost::any& rData, UINT8 retryCount, bool forceSynchronous)
  170. {
  171. Request* req = 0;
  172. RequestID rid = 0;
  173. {
  174. // lock to acquire rid and push request to the queue
  175. CM_LOCK_MUTEX(mRequestMutex)
  176. if (!mAcceptRequests || mShuttingDown)
  177. return 0;
  178. rid = ++mRequestCount;
  179. req = cm_new<Request, ScratchAlloc>(channel, rData, retryCount, rid);
  180. #if CM_THREAD_SUPPORT
  181. if (!forceSynchronous)
  182. {
  183. mRequestQueue.push_back(req);
  184. notifyWorkers();
  185. return rid;
  186. }
  187. #endif
  188. }
  189. processRequestResponse(req);
  190. return rid;
  191. }
  192. //---------------------------------------------------------------------
  193. void WorkQueue::addRequestWithRID(WorkQueue::RequestID rid, UINT16 channel,
  194. const boost::any& rData, UINT8 retryCount)
  195. {
  196. // lock to push request to the queue
  197. CM_LOCK_MUTEX(mRequestMutex)
  198. if (mShuttingDown)
  199. return;
  200. Request* req = cm_new<Request, ScratchAlloc>(channel, rData, retryCount, rid);
  201. #if CM_THREAD_SUPPORT
  202. mRequestQueue.push_back(req);
  203. notifyWorkers();
  204. #else
  205. processRequestResponse(req);
  206. #endif
  207. }
  208. //---------------------------------------------------------------------
  209. void WorkQueue::abortRequest(RequestID id)
  210. {
  211. CM_LOCK_MUTEX(mProcessMutex)
  212. // NOTE: Pending requests are exist any of RequestQueue, ProcessQueue and
  213. // ResponseQueue when keeping ProcessMutex, so we check all of these queues.
  214. for (RequestQueue::iterator i = mProcessQueue.begin(); i != mProcessQueue.end(); ++i)
  215. {
  216. if ((*i)->getID() == id)
  217. {
  218. (*i)->abortRequest();
  219. break;
  220. }
  221. }
  222. {
  223. CM_LOCK_MUTEX(mRequestMutex)
  224. for (RequestQueue::iterator i = mRequestQueue.begin(); i != mRequestQueue.end(); ++i)
  225. {
  226. if ((*i)->getID() == id)
  227. {
  228. (*i)->abortRequest();
  229. break;
  230. }
  231. }
  232. }
  233. }
  234. //---------------------------------------------------------------------
  235. void WorkQueue::abortRequestsByChannel(UINT16 channel)
  236. {
  237. CM_LOCK_MUTEX(mProcessMutex)
  238. for (RequestQueue::iterator i = mProcessQueue.begin(); i != mProcessQueue.end(); ++i)
  239. {
  240. if ((*i)->getChannel() == channel)
  241. {
  242. (*i)->abortRequest();
  243. }
  244. }
  245. {
  246. CM_LOCK_MUTEX(mRequestMutex)
  247. for (RequestQueue::iterator i = mRequestQueue.begin(); i != mRequestQueue.end(); ++i)
  248. {
  249. if ((*i)->getChannel() == channel)
  250. {
  251. (*i)->abortRequest();
  252. }
  253. }
  254. }
  255. }
  256. //---------------------------------------------------------------------
  257. void WorkQueue::abortAllRequests()
  258. {
  259. CM_LOCK_MUTEX(mProcessMutex)
  260. for (RequestQueue::iterator i = mProcessQueue.begin(); i != mProcessQueue.end(); ++i)
  261. {
  262. (*i)->abortRequest();
  263. }
  264. {
  265. CM_LOCK_MUTEX(mRequestMutex)
  266. for (RequestQueue::iterator i = mRequestQueue.begin(); i != mRequestQueue.end(); ++i)
  267. {
  268. (*i)->abortRequest();
  269. }
  270. }
  271. }
  272. //---------------------------------------------------------------------
  273. void WorkQueue::setPaused(bool pause)
  274. {
  275. CM_LOCK_MUTEX(mRequestMutex)
  276. mPaused = pause;
  277. }
  278. //---------------------------------------------------------------------
  279. bool WorkQueue::isPaused() const
  280. {
  281. return mPaused;
  282. }
  283. //---------------------------------------------------------------------
  284. void WorkQueue::setRequestsAccepted(bool accept)
  285. {
  286. CM_LOCK_MUTEX(mRequestMutex)
  287. mAcceptRequests = accept;
  288. }
  289. //---------------------------------------------------------------------
  290. bool WorkQueue::getRequestsAccepted() const
  291. {
  292. return mAcceptRequests;
  293. }
  294. //---------------------------------------------------------------------
  295. size_t WorkQueue::getWorkerThreadCount() const
  296. {
  297. return mWorkerThreadCount;
  298. }
  299. //---------------------------------------------------------------------
  300. void WorkQueue::setWorkerThreadCount(size_t c)
  301. {
  302. mWorkerThreadCount = c;
  303. }
  304. //---------------------------------------------------------------------
  305. UINT16 WorkQueue::getChannel(const String& channelName)
  306. {
  307. CM_LOCK_MUTEX(mChannelMapMutex)
  308. ChannelMap::iterator i = mChannelMap.find(channelName);
  309. if (i == mChannelMap.end())
  310. {
  311. i = mChannelMap.insert(ChannelMap::value_type(channelName, mNextChannel++)).first;
  312. }
  313. return i->second;
  314. }
  315. //---------------------------------------------------------------------
  316. void WorkQueue::processRequestResponse(Request* r)
  317. {
  318. Response* response = processRequest(r);
  319. CM_LOCK_MUTEX(mProcessMutex)
  320. RequestQueue::iterator it;
  321. for( it = mProcessQueue.begin(); it != mProcessQueue.end(); ++it )
  322. {
  323. if( (*it) == r )
  324. {
  325. mProcessQueue.erase( it );
  326. break;
  327. }
  328. }
  329. if (response)
  330. {
  331. if (!response->succeeded())
  332. {
  333. // Failed, should we retry?
  334. const Request* req = response->getRequest();
  335. if (req->getRetryCount())
  336. {
  337. addRequestWithRID(req->getID(), req->getChannel(), req->getData(),
  338. req->getRetryCount() - 1);
  339. // discard response (this also deletes request)
  340. CM_DELETE(response, Response, ScratchAlloc);
  341. return;
  342. }
  343. }
  344. processResponse(response);
  345. CM_DELETE(response, Response, ScratchAlloc);
  346. }
  347. else
  348. {
  349. // no response, delete request
  350. gDebug().logWarning("warning: no handler processed request "
  351. + toString(r->getID()) + ", channel " + toString(r->getChannel()));
  352. CM_DELETE(r, Request, ScratchAlloc);
  353. }
  354. }
  355. WorkQueue::Response* WorkQueue::processRequest(Request* r)
  356. {
  357. RequestHandlerListByChannel handlerListCopy;
  358. {
  359. // lock the list only to make a copy of it, to maximise parallelism
  360. CM_LOCK_RW_MUTEX_READ(mRequestHandlerMutex);
  361. handlerListCopy = mRequestHandlers;
  362. }
  363. Response* response = 0;
  364. RequestHandlerListByChannel::iterator i = handlerListCopy.find(r->getChannel());
  365. if (i != handlerListCopy.end())
  366. {
  367. RequestHandlerList& handlers = i->second;
  368. for (RequestHandlerList::reverse_iterator j = handlers.rbegin(); j != handlers.rend(); ++j)
  369. {
  370. // threadsafe call which tests canHandleRequest and calls it if so
  371. response = (*j)->handleRequest(r, this);
  372. if (response)
  373. break;
  374. }
  375. }
  376. return response;
  377. }
  378. //---------------------------------------------------------------------
  379. void WorkQueue::processResponse(Response* r)
  380. {
  381. ResponseHandlerListByChannel::iterator i = mResponseHandlers.find(r->getRequest()->getChannel());
  382. if (i != mResponseHandlers.end())
  383. {
  384. ResponseHandlerList& handlers = i->second;
  385. for (ResponseHandlerList::reverse_iterator j = handlers.rbegin(); j != handlers.rend(); ++j)
  386. {
  387. if ((*j)->canHandleResponse(r, this))
  388. {
  389. (*j)->handleResponse(r, this);
  390. }
  391. }
  392. }
  393. }
  394. //---------------------------------------------------------------------
  395. void WorkQueue::processNextRequest()
  396. {
  397. Request* request = 0;
  398. {
  399. // scoped to only lock while retrieving the next request
  400. CM_LOCK_MUTEX(mProcessMutex)
  401. {
  402. CM_LOCK_MUTEX(mRequestMutex)
  403. if (!mRequestQueue.empty())
  404. {
  405. request = mRequestQueue.front();
  406. mRequestQueue.pop_front();
  407. mProcessQueue.push_back( request );
  408. }
  409. }
  410. }
  411. if (request)
  412. {
  413. processRequestResponse(request);
  414. }
  415. }
  416. //---------------------------------------------------------------------
  417. void WorkQueue::waitForNextRequest()
  418. {
  419. #if CM_THREAD_SUPPORT
  420. // Lock; note that OGRE_THREAD_WAIT will free the lock
  421. CM_LOCK_MUTEX_NAMED(mRequestMutex, queueLock);
  422. if (mRequestQueue.empty())
  423. {
  424. // frees lock and suspends the thread
  425. CM_THREAD_WAIT(mRequestCondition, mRequestMutex, queueLock);
  426. }
  427. // When we get back here, it's because we've been notified
  428. // and thus the thread has been woken up. Lock has also been
  429. // re-acquired, but we won't use it. It's safe to try processing and fail
  430. // if another thread has got in first and grabbed the request
  431. #endif
  432. }
  433. //---------------------------------------------------------------------
  434. void WorkQueue::threadMain()
  435. {
  436. // default worker thread
  437. #if CM_THREAD_SUPPORT
  438. // Spin forever until we're told to shut down
  439. while (!isShuttingDown())
  440. {
  441. waitForNextRequest();
  442. processNextRequest();
  443. }
  444. #endif
  445. }
  446. //---------------------------------------------------------------------
  447. void WorkQueue::notifyWorkers()
  448. {
  449. // wake up waiting thread
  450. CM_THREAD_NOTIFY_ONE(mRequestCondition)
  451. }
  452. //---------------------------------------------------------------------
  453. WorkQueue::Request::Request(UINT16 channel, const boost::any& rData, UINT8 retry, RequestID rid)
  454. : mChannel(channel), mData(rData), mRetryCount(retry), mID(rid), mAborted(false)
  455. {
  456. }
  457. //---------------------------------------------------------------------
  458. WorkQueue::Request::~Request()
  459. {
  460. }
  461. //---------------------------------------------------------------------
  462. //---------------------------------------------------------------------
  463. WorkQueue::Response::Response(Request* rq, bool success, const boost::any& data)
  464. : mRequest(rq), mSuccess(success), mData(data)
  465. {
  466. }
  467. //---------------------------------------------------------------------
  468. WorkQueue::Response::~Response()
  469. {
  470. CM_DELETE(mRequest, Request, ScratchAlloc);
  471. }
  472. //---------------------------------------------------------------------
  473. void WorkQueue::WorkerFunc::operator()()
  474. {
  475. mQueue->threadMain();
  476. }
  477. void WorkQueue::WorkerFunc::run()
  478. {
  479. mQueue->threadMain();
  480. }
  481. }