CmWorkQueue.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  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. // keep going until we run out of responses
  325. while(true)
  326. {
  327. Response* response = 0;
  328. {
  329. CM_LOCK_MUTEX(mResponseMutex)
  330. if (mResponseQueue.empty())
  331. break; // exit loop
  332. else
  333. {
  334. response = mResponseQueue.front();
  335. mResponseQueue.pop_front();
  336. }
  337. }
  338. if (response)
  339. {
  340. processResponse(response);
  341. delete response;
  342. }
  343. }
  344. }
  345. //---------------------------------------------------------------------
  346. void WorkQueue::processRequestResponse(Request* r, bool synchronous)
  347. {
  348. Response* response = processRequest(r);
  349. CM_LOCK_MUTEX(mProcessMutex)
  350. RequestQueue::iterator it;
  351. for( it = mProcessQueue.begin(); it != mProcessQueue.end(); ++it )
  352. {
  353. if( (*it) == r )
  354. {
  355. mProcessQueue.erase( it );
  356. break;
  357. }
  358. }
  359. if (response)
  360. {
  361. if (!response->succeeded())
  362. {
  363. // Failed, should we retry?
  364. const Request* req = response->getRequest();
  365. if (req->getRetryCount())
  366. {
  367. addRequestWithRID(req->getID(), req->getChannel(), req->getData(),
  368. req->getRetryCount() - 1);
  369. // discard response (this also deletes request)
  370. delete response;
  371. return;
  372. }
  373. }
  374. if (synchronous)
  375. {
  376. processResponse(response);
  377. delete response;
  378. }
  379. else
  380. {
  381. if( response->getRequest()->getAborted() )
  382. {
  383. // destroy response user data
  384. response->abortRequest();
  385. }
  386. // Queue response
  387. CM_LOCK_MUTEX(mResponseMutex)
  388. mResponseQueue.push_back(response);
  389. // no need to wake thread, this is processed by the main thread
  390. }
  391. }
  392. else
  393. {
  394. // no response, delete request
  395. gDebug().logWarning("warning: no handler processed request "
  396. + toString(r->getID()) + ", channel " + toString(r->getChannel()));
  397. delete r;
  398. }
  399. }
  400. WorkQueue::Response* WorkQueue::processRequest(Request* r)
  401. {
  402. RequestHandlerListByChannel handlerListCopy;
  403. {
  404. // lock the list only to make a copy of it, to maximise parallelism
  405. CM_LOCK_RW_MUTEX_READ(mRequestHandlerMutex);
  406. handlerListCopy = mRequestHandlers;
  407. }
  408. Response* response = 0;
  409. RequestHandlerListByChannel::iterator i = handlerListCopy.find(r->getChannel());
  410. if (i != handlerListCopy.end())
  411. {
  412. RequestHandlerList& handlers = i->second;
  413. for (RequestHandlerList::reverse_iterator j = handlers.rbegin(); j != handlers.rend(); ++j)
  414. {
  415. // threadsafe call which tests canHandleRequest and calls it if so
  416. response = (*j)->handleRequest(r, this);
  417. if (response)
  418. break;
  419. }
  420. }
  421. return response;
  422. }
  423. //---------------------------------------------------------------------
  424. void WorkQueue::processResponse(Response* r)
  425. {
  426. ResponseHandlerListByChannel::iterator i = mResponseHandlers.find(r->getRequest()->getChannel());
  427. if (i != mResponseHandlers.end())
  428. {
  429. ResponseHandlerList& handlers = i->second;
  430. for (ResponseHandlerList::reverse_iterator j = handlers.rbegin(); j != handlers.rend(); ++j)
  431. {
  432. if ((*j)->canHandleResponse(r, this))
  433. {
  434. (*j)->handleResponse(r, this);
  435. }
  436. }
  437. }
  438. }
  439. //---------------------------------------------------------------------
  440. void WorkQueue::addRequestWithRID(WorkQueue::RequestID rid, UINT16 channel,
  441. const boost::any& rData, UINT8 retryCount)
  442. {
  443. // lock to push request to the queue
  444. CM_LOCK_MUTEX(mRequestMutex)
  445. if (mShuttingDown)
  446. return;
  447. Request* req = new Request(channel, rData, retryCount, rid);
  448. #if CM_THREAD_SUPPORT
  449. mRequestQueue.push_back(req);
  450. notifyWorkers();
  451. #else
  452. processRequestResponse(req, true);
  453. #endif
  454. }
  455. //---------------------------------------------------------------------
  456. void WorkQueue::processNextRequest()
  457. {
  458. Request* request = 0;
  459. {
  460. // scoped to only lock while retrieving the next request
  461. CM_LOCK_MUTEX(mProcessMutex)
  462. {
  463. CM_LOCK_MUTEX(mRequestMutex)
  464. if (!mRequestQueue.empty())
  465. {
  466. request = mRequestQueue.front();
  467. mRequestQueue.pop_front();
  468. mProcessQueue.push_back( request );
  469. }
  470. }
  471. }
  472. if (request)
  473. {
  474. processRequestResponse(request, false);
  475. }
  476. }
  477. //---------------------------------------------------------------------
  478. void WorkQueue::waitForNextRequest()
  479. {
  480. #if CM_THREAD_SUPPORT
  481. // Lock; note that OGRE_THREAD_WAIT will free the lock
  482. CM_LOCK_MUTEX_NAMED(mRequestMutex, queueLock);
  483. if (mRequestQueue.empty())
  484. {
  485. // frees lock and suspends the thread
  486. CM_THREAD_WAIT(mRequestCondition, mRequestMutex, queueLock);
  487. }
  488. // When we get back here, it's because we've been notified
  489. // and thus the thread has been woken up. Lock has also been
  490. // re-acquired, but we won't use it. It's safe to try processing and fail
  491. // if another thread has got in first and grabbed the request
  492. #endif
  493. }
  494. //---------------------------------------------------------------------
  495. void WorkQueue::threadMain()
  496. {
  497. // default worker thread
  498. #if CM_THREAD_SUPPORT
  499. // Spin forever until we're told to shut down
  500. while (!isShuttingDown())
  501. {
  502. waitForNextRequest();
  503. processNextRequest();
  504. }
  505. #endif
  506. }
  507. //---------------------------------------------------------------------
  508. void WorkQueue::notifyWorkers()
  509. {
  510. // wake up waiting thread
  511. CM_THREAD_NOTIFY_ONE(mRequestCondition)
  512. }
  513. //---------------------------------------------------------------------
  514. WorkQueue::Request::Request(UINT16 channel, const boost::any& rData, UINT8 retry, RequestID rid)
  515. : mChannel(channel), mData(rData), mRetryCount(retry), mID(rid), mAborted(false)
  516. {
  517. }
  518. //---------------------------------------------------------------------
  519. WorkQueue::Request::~Request()
  520. {
  521. }
  522. //---------------------------------------------------------------------
  523. //---------------------------------------------------------------------
  524. WorkQueue::Response::Response(const Request* rq, bool success, const boost::any& data)
  525. : mRequest(rq), mSuccess(success), mData(data)
  526. {
  527. }
  528. //---------------------------------------------------------------------
  529. WorkQueue::Response::~Response()
  530. {
  531. delete mRequest;
  532. }
  533. //---------------------------------------------------------------------
  534. void WorkQueue::WorkerFunc::operator()()
  535. {
  536. mQueue->threadMain();
  537. }
  538. void WorkQueue::WorkerFunc::run()
  539. {
  540. mQueue->threadMain();
  541. }
  542. }