BsCommandQueue.h 12 KB

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