CmWorkQueue.cpp 14 KB

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