CmCommandQueue.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. #pragma once
  2. #include "CmPrerequisites.h"
  3. #include "CmAsyncOp.h"
  4. #include "CmCommonEnums.h"
  5. #include "boost/function.hpp"
  6. #include <functional>
  7. namespace CamelotFramework
  8. {
  9. class CommandQueueNoSync
  10. {
  11. public:
  12. CommandQueueNoSync() {}
  13. virtual ~CommandQueueNoSync() {}
  14. bool isValidThread(CM_THREAD_ID_TYPE ownerThread) const
  15. {
  16. return CM_THREAD_CURRENT_ID == ownerThread;
  17. }
  18. void lock()
  19. {
  20. };
  21. void unlock()
  22. {
  23. }
  24. };
  25. class CommandQueueSync
  26. {
  27. public:
  28. CommandQueueSync()
  29. :mLock(mCommandQueueMutex, boost::defer_lock)
  30. { }
  31. virtual ~CommandQueueSync() {}
  32. bool isValidThread(CM_THREAD_ID_TYPE ownerThread) const
  33. {
  34. return true;
  35. }
  36. void lock()
  37. {
  38. mLock.lock();
  39. };
  40. void unlock()
  41. {
  42. mLock.unlock();
  43. }
  44. private:
  45. CM_MUTEX(mCommandQueueMutex);
  46. CM_LOCK_TYPE mLock;
  47. };
  48. struct QueuedCommand
  49. {
  50. #if CM_DEBUG_MODE
  51. QueuedCommand(boost::function<void(AsyncOp&)> _callback, UINT32 _debugId, bool _notifyWhenComplete = false, UINT32 _callbackId = 0)
  52. :callbackWithReturnValue(_callback), debugId(_debugId), returnsValue(true), notifyWhenComplete(_notifyWhenComplete), callbackId(_callbackId), asyncOp(cm_new<AsyncOp>()), ownsData(true)
  53. { }
  54. QueuedCommand(boost::function<void()> _callback, UINT32 _debugId, bool _notifyWhenComplete = false, UINT32 _callbackId = 0)
  55. :callback(_callback), debugId(_debugId), returnsValue(false), notifyWhenComplete(_notifyWhenComplete), callbackId(_callbackId), asyncOp(nullptr), ownsData(true)
  56. { }
  57. UINT32 debugId;
  58. #else
  59. QueuedCommand(boost::function<void(AsyncOp&)> _callback, bool _notifyWhenComplete = false, UINT32 _callbackId = 0)
  60. :callbackWithReturnValue(_callback), returnsValue(true), notifyWhenComplete(_notifyWhenComplete), callbackId(_callbackId), asyncOp(cm_new<AsyncOp>()), ownsData(true)
  61. { }
  62. QueuedCommand(boost::function<void()> _callback, bool _notifyWhenComplete = false, UINT32 _callbackId = 0)
  63. :callback(_callback), returnsValue(false), notifyWhenComplete(_notifyWhenComplete), callbackId(_callbackId), asyncOp(nullptr), ownsData(true)
  64. { }
  65. #endif
  66. ~QueuedCommand()
  67. {
  68. if(ownsData && asyncOp != nullptr)
  69. cm_delete(asyncOp);
  70. }
  71. QueuedCommand(const QueuedCommand& source)
  72. {
  73. ownsData = true;
  74. source.ownsData = false;
  75. callback = source.callback;
  76. callbackWithReturnValue = source.callbackWithReturnValue;
  77. asyncOp = source.asyncOp;
  78. returnsValue = source.returnsValue;
  79. callbackId = source.callbackId;
  80. notifyWhenComplete = source.notifyWhenComplete;
  81. }
  82. QueuedCommand& operator=(const QueuedCommand& rhs)
  83. {
  84. ownsData = true;
  85. rhs.ownsData = false;
  86. callback = rhs.callback;
  87. callbackWithReturnValue = rhs.callbackWithReturnValue;
  88. asyncOp = rhs.asyncOp;
  89. returnsValue = rhs.returnsValue;
  90. callbackId = rhs.callbackId;
  91. notifyWhenComplete = rhs.notifyWhenComplete;
  92. return *this;
  93. }
  94. boost::function<void()> callback;
  95. boost::function<void(AsyncOp&)> callbackWithReturnValue;
  96. AsyncOp* asyncOp;
  97. bool returnsValue;
  98. UINT32 callbackId;
  99. bool notifyWhenComplete;
  100. mutable bool ownsData;
  101. };
  102. /**
  103. * @brief Contains a list of commands that can be queued by one thread,
  104. * and executed by another.
  105. */
  106. class CM_EXPORT CommandQueueBase
  107. {
  108. public:
  109. /**
  110. * @brief Constructor.
  111. *
  112. * @param threadId Identifier for the thread the command queue will be used on.
  113. */
  114. CommandQueueBase(CM_THREAD_ID_TYPE threadId);
  115. virtual ~CommandQueueBase();
  116. CM_THREAD_ID_TYPE getThreadId() const { return mMyThreadId; }
  117. /**
  118. * @brief Plays all provided commands. To get the commands call flush().
  119. *
  120. * @param notifyCallback Callback that will be called if a command that has "notifyOnComplete" flag set.
  121. * The callback will receive "callbackId" of the command.
  122. */
  123. void playback(Queue<QueuedCommand>::type* commands, boost::function<void(UINT32)> notifyCallback);
  124. /**
  125. * @brief Plays all provided commands. To get the commands call flush().
  126. */
  127. void playback(Queue<QueuedCommand>::type* commands);
  128. /**
  129. * @brief Allows you to set a breakpoint that will trigger when the specified command is executed.
  130. *
  131. * @note This is helpful when you receive an error on the executing thread and you cannot tell from where was
  132. * the command that caused the error queued from. However you can make a note of the queue and command index
  133. * and set a breakpoint so that it gets triggered next time you run the program. At that point you can know
  134. * exactly which part of code queued the command by examining the stack trace.
  135. *
  136. * @param queueIdx Zero-based index of the queue the command was queued on.
  137. * @param commandIdx Zero-based index of the command.
  138. */
  139. static void addBreakpoint(UINT32 queueIdx, UINT32 commandIdx);
  140. protected:
  141. /**
  142. * @brief Queue up a new command to execute. Make sure the provided function has all of its
  143. * parameters properly bound. Last parameter must be unbound and of AsyncOp&amp; type.
  144. * This is used to signal that the command is completed, and also for storing the return
  145. * value.
  146. *
  147. * @note Callback method also needs to call AsyncOp::markAsResolved once it is done
  148. * processing. (If it doesn't it will still be called automatically, but the return
  149. * value will default to nullptr)
  150. *
  151. * @param _notifyWhenComplete (optional) Call the notify method (provided in the call to CommandQueue::playback)
  152. * when the command is complete.
  153. * @param _callbackId (optional) Identifier for the callback so you can then later find it
  154. * if needed.
  155. *
  156. * @return Async operation object you can continuously check until the command completes. After
  157. * it completes AsyncOp::isResolved will return true and return data will be valid (if
  158. * the callback provided any).
  159. */
  160. AsyncOp queueReturn(boost::function<void(AsyncOp&)> commandCallback, bool _notifyWhenComplete = false, UINT32 _callbackId = 0);
  161. /**
  162. * @brief Queue up a new command to execute. Make sure the provided function has all of its
  163. * parameters properly bound. Provided command is not expected to return a value. If you
  164. * wish to return a value from the callback use the other overload of queueCommand which
  165. * accepts AsyncOp parameter.
  166. *
  167. * @param _notifyWhenComplete (optional) Call the notify method (provided in the call to CommandQueue::playback)
  168. * when the command is complete.
  169. * @param _callbackId (optional) Identifier for the callback so you can then later find
  170. * it if needed.
  171. */
  172. void queue(boost::function<void()> commandCallback, bool _notifyWhenComplete = false, UINT32 _callbackId = 0);
  173. /**
  174. * @brief Returns a copy of all queued commands and makes room for new ones. Must be called from the thread
  175. * that created the command queue. Returned commands MUST be passed to "playback" method.
  176. */
  177. CamelotFramework::Queue<QueuedCommand>::type* flush();
  178. /**
  179. * @brief Cancels all currently queued commands.
  180. */
  181. void cancelAll();
  182. /**
  183. * @brief Returns true if no commands are queued.
  184. */
  185. bool isEmpty();
  186. protected:
  187. void throwInvalidThreadException(const String& message) const;
  188. private:
  189. CamelotFramework::Queue<QueuedCommand>::type* mCommands;
  190. Stack<CamelotFramework::Queue<QueuedCommand>::type*>::type mEmptyCommandQueues; // List of empty queues for reuse
  191. CM_THREAD_ID_TYPE mMyThreadId;
  192. // Various variables that allow for easier debugging by allowing us to trigger breakpoints
  193. // when a certain command was queued.
  194. #if CM_DEBUG_MODE
  195. struct QueueBreakpoint
  196. {
  197. class HashFunction
  198. {
  199. public:
  200. size_t operator()(const QueueBreakpoint &key) const;
  201. };
  202. class EqualFunction
  203. {
  204. public:
  205. bool operator()(const QueueBreakpoint &a, const QueueBreakpoint &b) const;
  206. };
  207. QueueBreakpoint(UINT32 _queueIdx, UINT32 _commandIdx)
  208. :queueIdx(_queueIdx), commandIdx(_commandIdx)
  209. { }
  210. UINT32 queueIdx;
  211. UINT32 commandIdx;
  212. inline size_t operator()(const QueueBreakpoint& v) const;
  213. };
  214. UINT32 mMaxDebugIdx;
  215. UINT32 mCommandQueueIdx;
  216. static UINT32 MaxCommandQueueIdx;
  217. static UnorderedSet<QueueBreakpoint, QueueBreakpoint::HashFunction, QueueBreakpoint::EqualFunction>::type SetBreakpoints;
  218. CM_STATIC_MUTEX(CommandQueueBreakpointMutex);
  219. static void breakIfNeeded(UINT32 queueIdx, UINT32 commandIdx);
  220. #endif
  221. };
  222. /**
  223. * @copydoc CommandQueueBase
  224. */
  225. template<class SyncPolicy = CommandQueueNoSync>
  226. class CommandQueue : public CommandQueueBase, public SyncPolicy
  227. {
  228. public:
  229. /**
  230. * @copydoc CommandQueueBase::CommandQueueBase
  231. */
  232. CommandQueue(CM_THREAD_ID_TYPE threadId)
  233. :CommandQueueBase(threadId)
  234. { }
  235. ~CommandQueue()
  236. {
  237. #if CM_DEBUG_MODE
  238. #if CM_THREAD_SUPPORT != 0
  239. if(!isValidThread(getThreadId()))
  240. throwInvalidThreadException("Command queue accessed outside of its creation thread.");
  241. #endif
  242. #endif
  243. }
  244. /**
  245. * @copydoc CommandQueueBase::queueReturn
  246. */
  247. AsyncOp queueReturn(boost::function<void(AsyncOp&)> commandCallback, bool _notifyWhenComplete = false, UINT32 _callbackId = 0)
  248. {
  249. #if CM_DEBUG_MODE
  250. #if CM_THREAD_SUPPORT != 0
  251. if(!isValidThread(getThreadId()))
  252. throwInvalidThreadException("Command queue accessed outside of its creation thread.");
  253. #endif
  254. #endif
  255. lock();
  256. AsyncOp asyncOp = CommandQueueBase::queueReturn(commandCallback, _notifyWhenComplete, _callbackId);
  257. unlock();
  258. return asyncOp;
  259. }
  260. /**
  261. * @copydoc CommandQueueBase::queue
  262. */
  263. void queue(boost::function<void()> commandCallback, bool _notifyWhenComplete = false, UINT32 _callbackId = 0)
  264. {
  265. #if CM_DEBUG_MODE
  266. #if CM_THREAD_SUPPORT != 0
  267. if(!isValidThread(getThreadId()))
  268. throwInvalidThreadException("Command queue accessed outside of its creation thread.");
  269. #endif
  270. #endif
  271. lock();
  272. CommandQueueBase::queue(commandCallback, _notifyWhenComplete, _callbackId);
  273. unlock();
  274. }
  275. /**
  276. * @copydoc CommandQueueBase::flush
  277. */
  278. CamelotFramework::Queue<QueuedCommand>::type* flush()
  279. {
  280. #if CM_DEBUG_MODE
  281. #if CM_THREAD_SUPPORT != 0
  282. if(!isValidThread(getThreadId()))
  283. throwInvalidThreadException("Command queue accessed outside of its creation thread.");
  284. #endif
  285. #endif
  286. lock();
  287. CamelotFramework::Queue<QueuedCommand>::type* commands = CommandQueueBase::flush();
  288. unlock();
  289. return commands;
  290. }
  291. /**
  292. * @copydoc CommandQueueBase::cancelAll
  293. */
  294. void cancelAll()
  295. {
  296. #if CM_DEBUG_MODE
  297. #if CM_THREAD_SUPPORT != 0
  298. if(!isValidThread(getThreadId()))
  299. throwInvalidThreadException("Command queue accessed outside of its creation thread.");
  300. #endif
  301. #endif
  302. lock();
  303. CommandQueueBase::cancelAll();
  304. unlock();
  305. }
  306. /**
  307. * @copydoc CommandQueueBase::isEmpty
  308. */
  309. bool isEmpty()
  310. {
  311. #if CM_DEBUG_MODE
  312. #if CM_THREAD_SUPPORT != 0
  313. if(!isValidThread(getThreadId()))
  314. throwInvalidThreadException("Command queue accessed outside of its creation thread.");
  315. #endif
  316. #endif
  317. lock();
  318. bool empty = CommandQueueBase::isEmpty();
  319. unlock();
  320. return empty;
  321. }
  322. };
  323. }