CmWorkQueue.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  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 CamelotEngine {
  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. delete (*i);
  43. }
  44. mRequestQueue.clear();
  45. for (ResponseQueue::iterator i = mResponseQueue.begin(); i != mResponseQueue.end(); ++i)
  46. {
  47. delete (*i);
  48. }
  49. mResponseQueue.clear();
  50. }
  51. //---------------------------------------------------------------------
  52. void WorkQueue::startup(bool forceRestart)
  53. {
  54. if (mIsRunning)
  55. {
  56. if (forceRestart)
  57. shutdown();
  58. else
  59. return;
  60. }
  61. mShuttingDown = false;
  62. mWorkerFunc = new WorkerFunc(this);
  63. #if CM_THREAD_SUPPORT
  64. for (UINT8 i = 0; i < mWorkerThreadCount; ++i)
  65. {
  66. CM_THREAD_CREATE(t, *mWorkerFunc);
  67. mWorkers.push_back(t);
  68. }
  69. #endif
  70. mIsRunning = true;
  71. }
  72. //---------------------------------------------------------------------
  73. void WorkQueue::shutdown()
  74. {
  75. if( !mIsRunning )
  76. return;
  77. mShuttingDown = true;
  78. abortAllRequests();
  79. #if CM_THREAD_SUPPORT
  80. // wake all threads (they should check shutting down as first thing after wait)
  81. CM_THREAD_NOTIFY_ALL(mRequestCondition)
  82. // all our threads should have been woken now, so join
  83. for (WorkerThreadList::iterator i = mWorkers.begin(); i != mWorkers.end(); ++i)
  84. {
  85. (*i)->join();
  86. CM_THREAD_DESTROY(*i);
  87. }
  88. mWorkers.clear();
  89. #endif
  90. if (mWorkerFunc)
  91. {
  92. delete mWorkerFunc;
  93. mWorkerFunc = 0;
  94. }
  95. mIsRunning = false;
  96. }
  97. //---------------------------------------------------------------------
  98. void WorkQueue::addRequestHandler(UINT16 channel, RequestHandler* rh)
  99. {
  100. CM_LOCK_RW_MUTEX_WRITE(mRequestHandlerMutex);
  101. RequestHandlerListByChannel::iterator i = mRequestHandlers.find(channel);
  102. if (i == mRequestHandlers.end())
  103. i = mRequestHandlers.insert(RequestHandlerListByChannel::value_type(channel, RequestHandlerList())).first;
  104. RequestHandlerList& handlers = i->second;
  105. bool duplicate = false;
  106. for (RequestHandlerList::iterator j = handlers.begin(); j != handlers.end(); ++j)
  107. {
  108. if ((*j)->getHandler() == rh)
  109. {
  110. duplicate = true;
  111. break;
  112. }
  113. }
  114. if (!duplicate)
  115. handlers.push_back(RequestHandlerHolderPtr(new RequestHandlerHolder(rh)));
  116. }
  117. //---------------------------------------------------------------------
  118. void WorkQueue::removeRequestHandler(UINT16 channel, RequestHandler* rh)
  119. {
  120. CM_LOCK_RW_MUTEX_WRITE(mRequestHandlerMutex);
  121. RequestHandlerListByChannel::iterator i = mRequestHandlers.find(channel);
  122. if (i != mRequestHandlers.end())
  123. {
  124. RequestHandlerList& handlers = i->second;
  125. for (RequestHandlerList::iterator j = handlers.begin(); j != handlers.end(); ++j)
  126. {
  127. if ((*j)->getHandler() == rh)
  128. {
  129. // Disconnect - this will make it safe across copies of the list
  130. // this is threadsafe and will wait for existing processes to finish
  131. (*j)->disconnectHandler();
  132. handlers.erase(j);
  133. break;
  134. }
  135. }
  136. }
  137. }
  138. //---------------------------------------------------------------------
  139. void WorkQueue::addResponseHandler(UINT16 channel, ResponseHandler* rh)
  140. {
  141. ResponseHandlerListByChannel::iterator i = mResponseHandlers.find(channel);
  142. if (i == mResponseHandlers.end())
  143. i = mResponseHandlers.insert(ResponseHandlerListByChannel::value_type(channel, ResponseHandlerList())).first;
  144. ResponseHandlerList& handlers = i->second;
  145. if (std::find(handlers.begin(), handlers.end(), rh) == handlers.end())
  146. handlers.push_back(rh);
  147. }
  148. //---------------------------------------------------------------------
  149. void WorkQueue::removeResponseHandler(UINT16 channel, ResponseHandler* rh)
  150. {
  151. ResponseHandlerListByChannel::iterator i = mResponseHandlers.find(channel);
  152. if (i != mResponseHandlers.end())
  153. {
  154. ResponseHandlerList& handlers = i->second;
  155. ResponseHandlerList::iterator j = std::find(
  156. handlers.begin(), handlers.end(), rh);
  157. if (j != handlers.end())
  158. handlers.erase(j);
  159. }
  160. }
  161. //---------------------------------------------------------------------
  162. WorkQueue::RequestID WorkQueue::peekNextFreeRequestId()
  163. {
  164. {
  165. // lock to acquire rid and push request to the queue
  166. CM_LOCK_MUTEX(mRequestMutex)
  167. RequestID rid = mRequestCount + 1;
  168. return rid;
  169. }
  170. }
  171. //---------------------------------------------------------------------
  172. WorkQueue::RequestID WorkQueue::addRequest(UINT16 channel,
  173. const boost::any& rData, UINT8 retryCount, bool forceSynchronous)
  174. {
  175. Request* req = 0;
  176. RequestID rid = 0;
  177. {
  178. // lock to acquire rid and push request to the queue
  179. CM_LOCK_MUTEX(mRequestMutex)
  180. if (!mAcceptRequests || mShuttingDown)
  181. return 0;
  182. rid = ++mRequestCount;
  183. req = new Request(channel, rData, retryCount, rid);
  184. #if CM_THREAD_SUPPORT
  185. if (!forceSynchronous)
  186. {
  187. mRequestQueue.push_back(req);
  188. notifyWorkers();
  189. return rid;
  190. }
  191. #endif
  192. }
  193. processRequestResponse(req, true);
  194. return rid;
  195. }
  196. //---------------------------------------------------------------------
  197. void WorkQueue::addRequestWithRID(WorkQueue::RequestID rid, UINT16 channel,
  198. const boost::any& rData, UINT8 retryCount)
  199. {
  200. // lock to push request to the queue
  201. CM_LOCK_MUTEX(mRequestMutex)
  202. if (mShuttingDown)
  203. return;
  204. Request* req = new Request(channel, rData, retryCount, rid);
  205. #if CM_THREAD_SUPPORT
  206. mRequestQueue.push_back(req);
  207. notifyWorkers();
  208. #else
  209. processRequestResponse(req, true);
  210. #endif
  211. }
  212. //---------------------------------------------------------------------
  213. void WorkQueue::abortRequest(RequestID id)
  214. {
  215. CM_LOCK_MUTEX(mProcessMutex)
  216. // NOTE: Pending requests are exist any of RequestQueue, ProcessQueue and
  217. // ResponseQueue when keeping ProcessMutex, so we check all of these queues.
  218. for (RequestQueue::iterator i = mProcessQueue.begin(); i != mProcessQueue.end(); ++i)
  219. {
  220. if ((*i)->getID() == id)
  221. {
  222. (*i)->abortRequest();
  223. break;
  224. }
  225. }
  226. {
  227. CM_LOCK_MUTEX(mRequestMutex)
  228. for (RequestQueue::iterator i = mRequestQueue.begin(); i != mRequestQueue.end(); ++i)
  229. {
  230. if ((*i)->getID() == id)
  231. {
  232. (*i)->abortRequest();
  233. break;
  234. }
  235. }
  236. }
  237. {
  238. CM_LOCK_MUTEX(mResponseMutex)
  239. for (ResponseQueue::iterator i = mResponseQueue.begin(); i != mResponseQueue.end(); ++i)
  240. {
  241. if( (*i)->getRequest()->getID() == id )
  242. {
  243. (*i)->abortRequest();
  244. break;
  245. }
  246. }
  247. }
  248. }
  249. //---------------------------------------------------------------------
  250. void WorkQueue::abortRequestsByChannel(UINT16 channel)
  251. {
  252. CM_LOCK_MUTEX(mProcessMutex)
  253. for (RequestQueue::iterator i = mProcessQueue.begin(); i != mProcessQueue.end(); ++i)
  254. {
  255. if ((*i)->getChannel() == channel)
  256. {
  257. (*i)->abortRequest();
  258. }
  259. }
  260. {
  261. CM_LOCK_MUTEX(mRequestMutex)
  262. for (RequestQueue::iterator i = mRequestQueue.begin(); i != mRequestQueue.end(); ++i)
  263. {
  264. if ((*i)->getChannel() == channel)
  265. {
  266. (*i)->abortRequest();
  267. }
  268. }
  269. }
  270. {
  271. CM_LOCK_MUTEX(mResponseMutex)
  272. for (ResponseQueue::iterator i = mResponseQueue.begin(); i != mResponseQueue.end(); ++i)
  273. {
  274. if( (*i)->getRequest()->getChannel() == channel )
  275. {
  276. (*i)->abortRequest();
  277. }
  278. }
  279. }
  280. }
  281. //---------------------------------------------------------------------
  282. void WorkQueue::abortAllRequests()
  283. {
  284. CM_LOCK_MUTEX(mProcessMutex)
  285. for (RequestQueue::iterator i = mProcessQueue.begin(); i != mProcessQueue.end(); ++i)
  286. {
  287. (*i)->abortRequest();
  288. }
  289. {
  290. CM_LOCK_MUTEX(mRequestMutex)
  291. for (RequestQueue::iterator i = mRequestQueue.begin(); i != mRequestQueue.end(); ++i)
  292. {
  293. (*i)->abortRequest();
  294. }
  295. }
  296. {
  297. CM_LOCK_MUTEX(mResponseMutex)
  298. for (ResponseQueue::iterator i = mResponseQueue.begin(); i != mResponseQueue.end(); ++i)
  299. {
  300. (*i)->abortRequest();
  301. }
  302. }
  303. }
  304. //---------------------------------------------------------------------
  305. void WorkQueue::setPaused(bool pause)
  306. {
  307. CM_LOCK_MUTEX(mRequestMutex)
  308. mPaused = pause;
  309. }
  310. //---------------------------------------------------------------------
  311. bool WorkQueue::isPaused() const
  312. {
  313. return mPaused;
  314. }
  315. //---------------------------------------------------------------------
  316. void WorkQueue::setRequestsAccepted(bool accept)
  317. {
  318. CM_LOCK_MUTEX(mRequestMutex)
  319. mAcceptRequests = accept;
  320. }
  321. //---------------------------------------------------------------------
  322. bool WorkQueue::getRequestsAccepted() const
  323. {
  324. return mAcceptRequests;
  325. }
  326. //---------------------------------------------------------------------
  327. size_t WorkQueue::getWorkerThreadCount() const
  328. {
  329. return mWorkerThreadCount;
  330. }
  331. //---------------------------------------------------------------------
  332. void WorkQueue::setWorkerThreadCount(size_t c)
  333. {
  334. mWorkerThreadCount = c;
  335. }
  336. //---------------------------------------------------------------------
  337. UINT16 WorkQueue::getChannel(const String& channelName)
  338. {
  339. CM_LOCK_MUTEX(mChannelMapMutex)
  340. ChannelMap::iterator i = mChannelMap.find(channelName);
  341. if (i == mChannelMap.end())
  342. {
  343. i = mChannelMap.insert(ChannelMap::value_type(channelName, mNextChannel++)).first;
  344. }
  345. return i->second;
  346. }
  347. //---------------------------------------------------------------------
  348. void WorkQueue::processResponses()
  349. {
  350. // TODO Low priority - Processing a lot of responses can cause a frame rate spike. Maybe limit the processing to Xms?
  351. // keep going until we run out of responses
  352. while(true)
  353. {
  354. Response* response = 0;
  355. {
  356. CM_LOCK_MUTEX(mResponseMutex)
  357. if (mResponseQueue.empty())
  358. break; // exit loop
  359. else
  360. {
  361. response = mResponseQueue.front();
  362. mResponseQueue.pop_front();
  363. }
  364. }
  365. if (response)
  366. {
  367. processResponse(response);
  368. delete response;
  369. }
  370. }
  371. }
  372. //---------------------------------------------------------------------
  373. void WorkQueue::processRequestResponse(Request* r, bool synchronous)
  374. {
  375. Response* response = processRequest(r);
  376. CM_LOCK_MUTEX(mProcessMutex)
  377. RequestQueue::iterator it;
  378. for( it = mProcessQueue.begin(); it != mProcessQueue.end(); ++it )
  379. {
  380. if( (*it) == r )
  381. {
  382. mProcessQueue.erase( it );
  383. break;
  384. }
  385. }
  386. if (response)
  387. {
  388. if (!response->succeeded())
  389. {
  390. // Failed, should we retry?
  391. const Request* req = response->getRequest();
  392. if (req->getRetryCount())
  393. {
  394. addRequestWithRID(req->getID(), req->getChannel(), req->getData(),
  395. req->getRetryCount() - 1);
  396. // discard response (this also deletes request)
  397. delete response;
  398. return;
  399. }
  400. }
  401. if (synchronous)
  402. {
  403. processResponse(response);
  404. delete response;
  405. }
  406. else
  407. {
  408. if( response->getRequest()->getAborted() )
  409. {
  410. // destroy response user data
  411. response->abortRequest();
  412. }
  413. // Queue response
  414. CM_LOCK_MUTEX(mResponseMutex)
  415. mResponseQueue.push_back(response);
  416. // no need to wake thread, this is processed by the main thread
  417. }
  418. }
  419. else
  420. {
  421. // no response, delete request
  422. gDebug().logWarning("warning: no handler processed request "
  423. + toString(r->getID()) + ", channel " + toString(r->getChannel()));
  424. delete r;
  425. }
  426. }
  427. WorkQueue::Response* WorkQueue::processRequest(Request* r)
  428. {
  429. RequestHandlerListByChannel handlerListCopy;
  430. {
  431. // lock the list only to make a copy of it, to maximise parallelism
  432. CM_LOCK_RW_MUTEX_READ(mRequestHandlerMutex);
  433. handlerListCopy = mRequestHandlers;
  434. }
  435. Response* response = 0;
  436. RequestHandlerListByChannel::iterator i = handlerListCopy.find(r->getChannel());
  437. if (i != handlerListCopy.end())
  438. {
  439. RequestHandlerList& handlers = i->second;
  440. for (RequestHandlerList::reverse_iterator j = handlers.rbegin(); j != handlers.rend(); ++j)
  441. {
  442. // threadsafe call which tests canHandleRequest and calls it if so
  443. response = (*j)->handleRequest(r, this);
  444. if (response)
  445. break;
  446. }
  447. }
  448. return response;
  449. }
  450. //---------------------------------------------------------------------
  451. void WorkQueue::processResponse(Response* r)
  452. {
  453. ResponseHandlerListByChannel::iterator i = mResponseHandlers.find(r->getRequest()->getChannel());
  454. if (i != mResponseHandlers.end())
  455. {
  456. ResponseHandlerList& handlers = i->second;
  457. for (ResponseHandlerList::reverse_iterator j = handlers.rbegin(); j != handlers.rend(); ++j)
  458. {
  459. if ((*j)->canHandleResponse(r, this))
  460. {
  461. (*j)->handleResponse(r, this);
  462. }
  463. }
  464. }
  465. }
  466. //---------------------------------------------------------------------
  467. void WorkQueue::processNextRequest()
  468. {
  469. Request* request = 0;
  470. {
  471. // scoped to only lock while retrieving the next request
  472. CM_LOCK_MUTEX(mProcessMutex)
  473. {
  474. CM_LOCK_MUTEX(mRequestMutex)
  475. if (!mRequestQueue.empty())
  476. {
  477. request = mRequestQueue.front();
  478. mRequestQueue.pop_front();
  479. mProcessQueue.push_back( request );
  480. }
  481. }
  482. }
  483. if (request)
  484. {
  485. processRequestResponse(request, false);
  486. }
  487. }
  488. //---------------------------------------------------------------------
  489. void WorkQueue::waitForNextRequest()
  490. {
  491. #if CM_THREAD_SUPPORT
  492. // Lock; note that OGRE_THREAD_WAIT will free the lock
  493. CM_LOCK_MUTEX_NAMED(mRequestMutex, queueLock);
  494. if (mRequestQueue.empty())
  495. {
  496. // frees lock and suspends the thread
  497. CM_THREAD_WAIT(mRequestCondition, mRequestMutex, queueLock);
  498. }
  499. // When we get back here, it's because we've been notified
  500. // and thus the thread has been woken up. Lock has also been
  501. // re-acquired, but we won't use it. It's safe to try processing and fail
  502. // if another thread has got in first and grabbed the request
  503. #endif
  504. }
  505. //---------------------------------------------------------------------
  506. void WorkQueue::threadMain()
  507. {
  508. // default worker thread
  509. #if CM_THREAD_SUPPORT
  510. // Spin forever until we're told to shut down
  511. while (!isShuttingDown())
  512. {
  513. waitForNextRequest();
  514. processNextRequest();
  515. }
  516. #endif
  517. }
  518. //---------------------------------------------------------------------
  519. void WorkQueue::notifyWorkers()
  520. {
  521. // wake up waiting thread
  522. CM_THREAD_NOTIFY_ONE(mRequestCondition)
  523. }
  524. //---------------------------------------------------------------------
  525. WorkQueue::Request::Request(UINT16 channel, const boost::any& rData, UINT8 retry, RequestID rid)
  526. : mChannel(channel), mData(rData), mRetryCount(retry), mID(rid), mAborted(false)
  527. {
  528. }
  529. //---------------------------------------------------------------------
  530. WorkQueue::Request::~Request()
  531. {
  532. }
  533. //---------------------------------------------------------------------
  534. //---------------------------------------------------------------------
  535. WorkQueue::Response::Response(const Request* rq, bool success, const boost::any& data)
  536. : mRequest(rq), mSuccess(success), mData(data)
  537. {
  538. }
  539. //---------------------------------------------------------------------
  540. WorkQueue::Response::~Response()
  541. {
  542. delete mRequest;
  543. }
  544. //---------------------------------------------------------------------
  545. void WorkQueue::WorkerFunc::operator()()
  546. {
  547. mQueue->threadMain();
  548. }
  549. void WorkQueue::WorkerFunc::run()
  550. {
  551. mQueue->threadMain();
  552. }
  553. }