BsCommandQueue.h 12 KB

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