BsCommandQueue.h 12 KB

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