CmWorkQueue.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  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::addRequest(UINT16 channel,
  163. const boost::any& rData, UINT8 retryCount, bool forceSynchronous)
  164. {
  165. Request* req = 0;
  166. RequestID rid = 0;
  167. {
  168. // lock to acquire rid and push request to the queue
  169. CM_LOCK_MUTEX(mRequestMutex)
  170. if (!mAcceptRequests || mShuttingDown)
  171. return 0;
  172. rid = ++mRequestCount;
  173. req = new Request(channel, rData, retryCount, rid);
  174. #if CM_THREAD_SUPPORT
  175. if (!forceSynchronous)
  176. {
  177. mRequestQueue.push_back(req);
  178. notifyWorkers();
  179. return rid;
  180. }
  181. #endif
  182. }
  183. processRequestResponse(req, true);
  184. return rid;
  185. }
  186. //---------------------------------------------------------------------
  187. void WorkQueue::abortRequest(RequestID id)
  188. {
  189. CM_LOCK_MUTEX(mProcessMutex)
  190. // NOTE: Pending requests are exist any of RequestQueue, ProcessQueue and
  191. // ResponseQueue when keeping ProcessMutex, so we check all of these queues.
  192. for (RequestQueue::iterator i = mProcessQueue.begin(); i != mProcessQueue.end(); ++i)
  193. {
  194. if ((*i)->getID() == id)
  195. {
  196. (*i)->abortRequest();
  197. break;
  198. }
  199. }
  200. {
  201. CM_LOCK_MUTEX(mRequestMutex)
  202. for (RequestQueue::iterator i = mRequestQueue.begin(); i != mRequestQueue.end(); ++i)
  203. {
  204. if ((*i)->getID() == id)
  205. {
  206. (*i)->abortRequest();
  207. break;
  208. }
  209. }
  210. }
  211. {
  212. CM_LOCK_MUTEX(mResponseMutex)
  213. for (ResponseQueue::iterator i = mResponseQueue.begin(); i != mResponseQueue.end(); ++i)
  214. {
  215. if( (*i)->getRequest()->getID() == id )
  216. {
  217. (*i)->abortRequest();
  218. break;
  219. }
  220. }
  221. }
  222. }
  223. //---------------------------------------------------------------------
  224. void WorkQueue::abortRequestsByChannel(UINT16 channel)
  225. {
  226. CM_LOCK_MUTEX(mProcessMutex)
  227. for (RequestQueue::iterator i = mProcessQueue.begin(); i != mProcessQueue.end(); ++i)
  228. {
  229. if ((*i)->getChannel() == channel)
  230. {
  231. (*i)->abortRequest();
  232. }
  233. }
  234. {
  235. CM_LOCK_MUTEX(mRequestMutex)
  236. for (RequestQueue::iterator i = mRequestQueue.begin(); i != mRequestQueue.end(); ++i)
  237. {
  238. if ((*i)->getChannel() == channel)
  239. {
  240. (*i)->abortRequest();
  241. }
  242. }
  243. }
  244. {
  245. CM_LOCK_MUTEX(mResponseMutex)
  246. for (ResponseQueue::iterator i = mResponseQueue.begin(); i != mResponseQueue.end(); ++i)
  247. {
  248. if( (*i)->getRequest()->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. CM_LOCK_MUTEX(mResponseMutex)
  272. for (ResponseQueue::iterator i = mResponseQueue.begin(); i != mResponseQueue.end(); ++i)
  273. {
  274. (*i)->abortRequest();
  275. }
  276. }
  277. }
  278. //---------------------------------------------------------------------
  279. void WorkQueue::setPaused(bool pause)
  280. {
  281. CM_LOCK_MUTEX(mRequestMutex)
  282. mPaused = pause;
  283. }
  284. //---------------------------------------------------------------------
  285. bool WorkQueue::isPaused() const
  286. {
  287. return mPaused;
  288. }
  289. //---------------------------------------------------------------------
  290. void WorkQueue::setRequestsAccepted(bool accept)
  291. {
  292. CM_LOCK_MUTEX(mRequestMutex)
  293. mAcceptRequests = accept;
  294. }
  295. //---------------------------------------------------------------------
  296. bool WorkQueue::getRequestsAccepted() const
  297. {
  298. return mAcceptRequests;
  299. }
  300. //---------------------------------------------------------------------
  301. size_t WorkQueue::getWorkerThreadCount() const
  302. {
  303. return mWorkerThreadCount;
  304. }
  305. //---------------------------------------------------------------------
  306. void WorkQueue::setWorkerThreadCount(size_t c)
  307. {
  308. mWorkerThreadCount = c;
  309. }
  310. //---------------------------------------------------------------------
  311. UINT16 WorkQueue::getChannel(const String& channelName)
  312. {
  313. CM_LOCK_MUTEX(mChannelMapMutex)
  314. ChannelMap::iterator i = mChannelMap.find(channelName);
  315. if (i == mChannelMap.end())
  316. {
  317. i = mChannelMap.insert(ChannelMap::value_type(channelName, mNextChannel++)).first;
  318. }
  319. return i->second;
  320. }
  321. //---------------------------------------------------------------------
  322. void WorkQueue::processResponses()
  323. {
  324. // TODO Low priority - Processing a lot of responses can cause a frame rate spike. Maybe limit the processing to Xms?
  325. // keep going until we run out of responses
  326. while(true)
  327. {
  328. Response* response = 0;
  329. {
  330. CM_LOCK_MUTEX(mResponseMutex)
  331. if (mResponseQueue.empty())
  332. break; // exit loop
  333. else
  334. {
  335. response = mResponseQueue.front();
  336. mResponseQueue.pop_front();
  337. }
  338. }
  339. if (response)
  340. {
  341. processResponse(response);
  342. delete response;
  343. }
  344. }
  345. }
  346. //---------------------------------------------------------------------
  347. void WorkQueue::processRequestResponse(Request* r, bool synchronous)
  348. {
  349. Response* response = processRequest(r);
  350. CM_LOCK_MUTEX(mProcessMutex)
  351. RequestQueue::iterator it;
  352. for( it = mProcessQueue.begin(); it != mProcessQueue.end(); ++it )
  353. {
  354. if( (*it) == r )
  355. {
  356. mProcessQueue.erase( it );
  357. break;
  358. }
  359. }
  360. if (response)
  361. {
  362. if (!response->succeeded())
  363. {
  364. // Failed, should we retry?
  365. const Request* req = response->getRequest();
  366. if (req->getRetryCount())
  367. {
  368. addRequestWithRID(req->getID(), req->getChannel(), req->getData(),
  369. req->getRetryCount() - 1);
  370. // discard response (this also deletes request)
  371. delete response;
  372. return;
  373. }
  374. }
  375. if (synchronous)
  376. {
  377. processResponse(response);
  378. delete response;
  379. }
  380. else
  381. {
  382. if( response->getRequest()->getAborted() )
  383. {
  384. // destroy response user data
  385. response->abortRequest();
  386. }
  387. // Queue response
  388. CM_LOCK_MUTEX(mResponseMutex)
  389. mResponseQueue.push_back(response);
  390. // no need to wake thread, this is processed by the main thread
  391. }
  392. }
  393. else
  394. {
  395. // no response, delete request
  396. gDebug().logWarning("warning: no handler processed request "
  397. + toString(r->getID()) + ", channel " + toString(r->getChannel()));
  398. delete r;
  399. }
  400. }
  401. WorkQueue::Response* WorkQueue::processRequest(Request* r)
  402. {
  403. RequestHandlerListByChannel handlerListCopy;
  404. {
  405. // lock the list only to make a copy of it, to maximise parallelism
  406. CM_LOCK_RW_MUTEX_READ(mRequestHandlerMutex);
  407. handlerListCopy = mRequestHandlers;
  408. }
  409. Response* response = 0;
  410. RequestHandlerListByChannel::iterator i = handlerListCopy.find(r->getChannel());
  411. if (i != handlerListCopy.end())
  412. {
  413. RequestHandlerList& handlers = i->second;
  414. for (RequestHandlerList::reverse_iterator j = handlers.rbegin(); j != handlers.rend(); ++j)
  415. {
  416. // threadsafe call which tests canHandleRequest and calls it if so
  417. response = (*j)->handleRequest(r, this);
  418. if (response)
  419. break;
  420. }
  421. }
  422. return response;
  423. }
  424. //---------------------------------------------------------------------
  425. void WorkQueue::processResponse(Response* r)
  426. {
  427. ResponseHandlerListByChannel::iterator i = mResponseHandlers.find(r->getRequest()->getChannel());
  428. if (i != mResponseHandlers.end())
  429. {
  430. ResponseHandlerList& handlers = i->second;
  431. for (ResponseHandlerList::reverse_iterator j = handlers.rbegin(); j != handlers.rend(); ++j)
  432. {
  433. if ((*j)->canHandleResponse(r, this))
  434. {
  435. (*j)->handleResponse(r, this);
  436. }
  437. }
  438. }
  439. }
  440. //---------------------------------------------------------------------
  441. void WorkQueue::addRequestWithRID(WorkQueue::RequestID rid, UINT16 channel,
  442. const boost::any& rData, UINT8 retryCount)
  443. {
  444. // lock to push request to the queue
  445. CM_LOCK_MUTEX(mRequestMutex)
  446. if (mShuttingDown)
  447. return;
  448. Request* req = new Request(channel, rData, retryCount, rid);
  449. #if CM_THREAD_SUPPORT
  450. mRequestQueue.push_back(req);
  451. notifyWorkers();
  452. #else
  453. processRequestResponse(req, true);
  454. #endif
  455. }
  456. //---------------------------------------------------------------------
  457. void WorkQueue::processNextRequest()
  458. {
  459. Request* request = 0;
  460. {
  461. // scoped to only lock while retrieving the next request
  462. CM_LOCK_MUTEX(mProcessMutex)
  463. {
  464. CM_LOCK_MUTEX(mRequestMutex)
  465. if (!mRequestQueue.empty())
  466. {
  467. request = mRequestQueue.front();
  468. mRequestQueue.pop_front();
  469. mProcessQueue.push_back( request );
  470. }
  471. }
  472. }
  473. if (request)
  474. {
  475. processRequestResponse(request, false);
  476. }
  477. }
  478. //---------------------------------------------------------------------
  479. void WorkQueue::waitForNextRequest()
  480. {
  481. #if CM_THREAD_SUPPORT
  482. // Lock; note that OGRE_THREAD_WAIT will free the lock
  483. CM_LOCK_MUTEX_NAMED(mRequestMutex, queueLock);
  484. if (mRequestQueue.empty())
  485. {
  486. // frees lock and suspends the thread
  487. CM_THREAD_WAIT(mRequestCondition, mRequestMutex, queueLock);
  488. }
  489. // When we get back here, it's because we've been notified
  490. // and thus the thread has been woken up. Lock has also been
  491. // re-acquired, but we won't use it. It's safe to try processing and fail
  492. // if another thread has got in first and grabbed the request
  493. #endif
  494. }
  495. //---------------------------------------------------------------------
  496. void WorkQueue::threadMain()
  497. {
  498. // default worker thread
  499. #if CM_THREAD_SUPPORT
  500. // Spin forever until we're told to shut down
  501. while (!isShuttingDown())
  502. {
  503. waitForNextRequest();
  504. processNextRequest();
  505. }
  506. #endif
  507. }
  508. //---------------------------------------------------------------------
  509. void WorkQueue::notifyWorkers()
  510. {
  511. // wake up waiting thread
  512. CM_THREAD_NOTIFY_ONE(mRequestCondition)
  513. }
  514. //---------------------------------------------------------------------
  515. WorkQueue::Request::Request(UINT16 channel, const boost::any& rData, UINT8 retry, RequestID rid)
  516. : mChannel(channel), mData(rData), mRetryCount(retry), mID(rid), mAborted(false)
  517. {
  518. }
  519. //---------------------------------------------------------------------
  520. WorkQueue::Request::~Request()
  521. {
  522. }
  523. //---------------------------------------------------------------------
  524. //---------------------------------------------------------------------
  525. WorkQueue::Response::Response(const Request* rq, bool success, const boost::any& data)
  526. : mRequest(rq), mSuccess(success), mData(data)
  527. {
  528. }
  529. //---------------------------------------------------------------------
  530. WorkQueue::Response::~Response()
  531. {
  532. delete mRequest;
  533. }
  534. //---------------------------------------------------------------------
  535. void WorkQueue::WorkerFunc::operator()()
  536. {
  537. mQueue->threadMain();
  538. }
  539. void WorkQueue::WorkerFunc::run()
  540. {
  541. mQueue->threadMain();
  542. }
  543. }