BsCommandQueue.h 12 KB

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