thread.hpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. /****************************************************************************
  2. *
  3. * Copyright (c) 2017, Michael Becker (michael.f.becker@gmail.com)
  4. *
  5. * This file is part of the FreeRTOS Add-ons project.
  6. *
  7. * Source Code:
  8. * https://github.com/michaelbecker/freertos-addons
  9. *
  10. * Project Page:
  11. * http://michaelbecker.github.io/freertos-addons/
  12. *
  13. * On-line Documentation:
  14. * http://michaelbecker.github.io/freertos-addons/docs/html/index.html
  15. *
  16. * Permission is hereby granted, free of charge, to any person obtaining a
  17. * copy of this software and associated documentation files
  18. * (the "Software"), to deal in the Software without restriction, including
  19. * without limitation the rights to use, copy, modify, merge, publish,
  20. * distribute, sublicense, and/or sell copies of the Software, and to
  21. * permit persons to whom the Software is furnished to do so,subject to the
  22. * following conditions:
  23. *
  24. * + The above copyright notice and this permission notice shall be included
  25. * in all copies or substantial portions of the Software.
  26. * + Credit is appreciated, but not required, if you find this project
  27. * useful enough to include in your application, product, device, etc.
  28. *
  29. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  30. * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  31. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  32. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  33. * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  34. * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  35. * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  36. *
  37. ***************************************************************************/
  38. #ifndef THREAD_HPP_
  39. #define THREAD_HPP_
  40. /**
  41. * The default in the C++ Wrapper classes is to use the C++ string class.
  42. * If you do not want this, define the following in your makefile or
  43. * project, and the Thread class will default to using character arrays
  44. * instead of C++ strings.
  45. *
  46. * @note If you define this, you also must define CPP_FREERTOS_NO_EXCEPTIONS.
  47. * Some classes throw exceptions if they cannot be constructed, and the
  48. * exceptions they throw depend on C++ strings.
  49. */
  50. #ifndef CPP_FREERTOS_NO_CPP_STRINGS
  51. #include <string>
  52. #endif
  53. #include "FreeRTOS.h"
  54. #include "task.h"
  55. #include "mutex.hpp"
  56. #include "semaphore.hpp"
  57. #include "condition_variable.hpp"
  58. namespace cpp_freertos {
  59. /**
  60. * Wrapper class around FreeRTOS's implementation of a task.
  61. *
  62. * This is an abstract base class.
  63. * To use this, you need to subclass it. All of your threads should
  64. * be derived from the Thread class. Then implement the virtual Run
  65. * function. This is a similar design to Java threading.
  66. *
  67. * By default, we leverage C++ strings for the Thread Name. If this
  68. * is not desirable, define CPP_FREERTOS_NO_CPP_STRINGS and the class
  69. * will fall back to C character arrays.
  70. */
  71. class Thread {
  72. /////////////////////////////////////////////////////////////////////////
  73. //
  74. // Public API
  75. // Available from anywhere. Many of these require a Thread reference
  76. // if they are operating on a thread.
  77. //
  78. /////////////////////////////////////////////////////////////////////////
  79. public:
  80. /**
  81. * Constructor to create a named thread.
  82. *
  83. * @param Name Name of the thread. Only useful for debugging.
  84. * @param StackDepth Number of "words" allocated for the Thread stack.
  85. * @param Priority FreeRTOS priority of this Thread.
  86. */
  87. #ifndef CPP_FREERTOS_NO_CPP_STRINGS
  88. Thread( const std::string Name,
  89. uint16_t StackDepth,
  90. UBaseType_t Priority);
  91. #else
  92. Thread( const char *Name,
  93. uint16_t StackDepth,
  94. UBaseType_t Priority);
  95. #endif
  96. /**
  97. * Constructor to create an unnamed thread.
  98. *
  99. * @param StackDepth Number of "words" allocated for the Thread stack.
  100. * @param Priority FreeRTOS priority of this Thread.
  101. */
  102. Thread( uint16_t StackDepth,
  103. UBaseType_t Priority);
  104. /**
  105. * Starts a thread.
  106. *
  107. * This is the API call that actually starts the thread running.
  108. * It creates a backing FreeRTOS task. By separating object creation
  109. * from starting the Thread, it solves the pure virtual fuction call
  110. * failure case. If we attempt to automatically call xTaskCreate
  111. * from the base class constructor, in certain conditions the task
  112. * starts to run "before" the derived class is constructed! So we
  113. * don't do that anymore.
  114. *
  115. * This may be called from your ctor once you have completed
  116. * your objects construction (so as the last step).
  117. *
  118. * This should only be called once ever!
  119. */
  120. bool Start();
  121. /**
  122. * Our destructor. This must exist even if FreeRTOS is
  123. * configured to disallow task deletion.
  124. */
  125. virtual ~Thread();
  126. /**
  127. * Accessor to get the thread's backing task handle.
  128. * There is no setter, on purpose.
  129. *
  130. * @return FreeRTOS task handle.
  131. */
  132. inline TaskHandle_t GetHandle()
  133. {
  134. return handle;
  135. }
  136. /**
  137. * Yield the scheduler.
  138. */
  139. static inline void Yield()
  140. {
  141. taskYIELD();
  142. }
  143. /**
  144. * Start the scheduler.
  145. *
  146. * @note You need to use this call. Do NOT directly call
  147. * vTaskStartScheduler while using this library.
  148. */
  149. static inline void StartScheduler()
  150. {
  151. SchedulerActive = true;
  152. vTaskStartScheduler();
  153. }
  154. /**
  155. * End the scheduler.
  156. *
  157. * @note Please see the FreeRTOS documentation regarding constraints
  158. * with the implementation of this.
  159. *
  160. * @note You need to use this call. Do NOT directly call
  161. * vTaskEndScheduler while using this library.
  162. */
  163. static inline void EndScheduler()
  164. {
  165. vTaskEndScheduler();
  166. SchedulerActive = false;
  167. }
  168. #if (INCLUDE_vTaskSuspend == 1)
  169. /**
  170. * Suspend this thread.
  171. *
  172. * @note While a Thread can Suspend() itself, it cannot Resume()
  173. * itself, becauseit's suspended.
  174. */
  175. inline void Suspend()
  176. {
  177. vTaskSuspend(GetHandle());
  178. }
  179. /**
  180. * Resume a specific thread.
  181. */
  182. inline void Resume()
  183. {
  184. vTaskResume(GetHandle());
  185. }
  186. #endif
  187. #if (INCLUDE_xTaskResumeFromISR == 1)
  188. /**
  189. * Resume a specific thread from ISR context.
  190. */
  191. inline void ResumeFromISR()
  192. {
  193. xTaskResumeFromISR(GetHandle());
  194. }
  195. #endif
  196. #if (INCLUDE_uxTaskPriorityGet == 1)
  197. /**
  198. * Get the priority of this Thread.
  199. *
  200. * @return Priority at the time this was called.
  201. */
  202. inline UBaseType_t GetPriority()
  203. {
  204. return (uxTaskPriorityGet(GetHandle()));
  205. }
  206. /**
  207. * Get the priority of this Thread from ISR context.
  208. *
  209. * @return Priority at the time this was called.
  210. */
  211. inline UBaseType_t GetPriorityFromISR()
  212. {
  213. return (uxTaskPriorityGetFromISR(GetHandle()));
  214. }
  215. #endif
  216. #if (INCLUDE_vTaskPrioritySet == 1)
  217. /**
  218. * Set the priority of this thread.
  219. *
  220. * @param NewPriority The thread's new priority.
  221. */
  222. inline void SetPriority(UBaseType_t NewPriority)
  223. {
  224. Priority = NewPriority;
  225. vTaskPrioritySet(GetHandle(), NewPriority);
  226. }
  227. #endif
  228. /**
  229. * Get the name of this thread.
  230. *
  231. * @return a C++ string with the name of the task.
  232. */
  233. #ifndef CPP_FREERTOS_NO_CPP_STRINGS
  234. inline std::string GetName()
  235. {
  236. return Name;
  237. }
  238. #else
  239. inline char* GetName()
  240. {
  241. return pcTaskGetName(handle);
  242. }
  243. #endif
  244. /////////////////////////////////////////////////////////////////////////
  245. //
  246. // Protected API
  247. // Available from inside your Thread implementation.
  248. // You should make sure that you are only calling these methods
  249. // from within your Run() method, or that your Run() method is on the
  250. // callstack.
  251. //
  252. /////////////////////////////////////////////////////////////////////////
  253. protected:
  254. /**
  255. * Implementation of your actual thread code.
  256. * You must override this function.
  257. * @note If INCLUDE_vTaskDelete is defined, then you may return from
  258. * your Run method. This will cause the task to be deleted from
  259. * FreeRTOS, however you are still responsible to delete the
  260. * task object. If this is not defined, then retuning from your Run()
  261. * method will result in an assert.
  262. */
  263. virtual void Run() = 0;
  264. #if (INCLUDE_vTaskDelete == 1)
  265. /**
  266. * Called on exit from your Run() routine.
  267. *
  268. * It is optional whether you implement this or not.
  269. *
  270. * If you allow your Thread to exit its Run method,
  271. * implementing a Cleanup method allows you to call
  272. * your Thread's destructor. If you decide to call delete
  273. * in your Cleanup function, be aware that additional
  274. * derived classes shouldn't call delete.
  275. */
  276. virtual void Cleanup();
  277. #else
  278. /**
  279. * If we can't delete a task, it makes no sense to have a
  280. * Cleanup routine.
  281. */
  282. #endif
  283. #if (INCLUDE_vTaskDelay == 1)
  284. /**
  285. * Delay this thread for at least Delay ticks.
  286. *
  287. * @param Delay How long to delay the thread.
  288. */
  289. void inline Delay(const TickType_t Delay)
  290. {
  291. vTaskDelay(Delay);
  292. }
  293. #endif
  294. #if (INCLUDE_vTaskDelayUntil == 1)
  295. /**
  296. * Delay this thread for Period ticks, taking into account
  297. * the execution time of the thread.
  298. *
  299. * This FreeRTOS permutation of delay can be used by periodic
  300. * tasks to ensure a constant execution frequency.
  301. *
  302. * @param Period How long to delay the thread.
  303. */
  304. void DelayUntil(const TickType_t Period);
  305. /**
  306. * If you need to adjust or reset the period of the
  307. * DelayUntil method.
  308. */
  309. void ResetDelayUntil();
  310. #endif
  311. #ifdef CPP_FREERTOS_CONDITION_VARIABLES
  312. /**
  313. * Have this thread wait on a condition variable.
  314. *
  315. * @note Threads wait, while ConditionVariables signal.
  316. *
  317. * @param Cv The condition variable associated with the Wait.
  318. * @param CvLock The required condition variable lock. The
  319. * Lock must be held before calling Wait.
  320. * @param Timeout Allows you to specify a timeout on the Wait,
  321. * if desired.
  322. *
  323. * @return true if the condition variable was signaled,
  324. * false if it timed out.
  325. */
  326. bool Wait( ConditionVariable &Cv,
  327. Mutex &CvLock,
  328. TickType_t Timeout = portMAX_DELAY);
  329. #endif
  330. /////////////////////////////////////////////////////////////////////////
  331. //
  332. // Private API
  333. // The internals of this wrapper class.
  334. //
  335. /////////////////////////////////////////////////////////////////////////
  336. private:
  337. /**
  338. * Reference to the underlying task handle for this thread.
  339. * Can be obtained from GetHandle().
  340. */
  341. TaskHandle_t handle;
  342. /**
  343. * We need to track whether the scheduler is active or not.
  344. */
  345. static volatile bool SchedulerActive;
  346. /**
  347. * The name of this thread.
  348. */
  349. #ifndef CPP_FREERTOS_NO_CPP_STRINGS
  350. const std::string Name;
  351. #else
  352. char Name[configMAX_TASK_NAME_LEN];
  353. #endif
  354. /**
  355. * Stack depth of this Thread, in words.
  356. */
  357. const uint16_t StackDepth;
  358. /**
  359. * A saved / cached copy of what the Thread's priority is.
  360. */
  361. UBaseType_t Priority;
  362. /**
  363. * Flag whether or not the Thread was started.
  364. */
  365. bool ThreadStarted;
  366. /**
  367. * Make sure no one calls Start more than once.
  368. */
  369. static MutexStandard StartGuardLock;
  370. /**
  371. * Adapter function that allows you to write a class
  372. * specific Run() function that interfaces with FreeRTOS.
  373. * Look at the implementation of the constructors and this
  374. * code to see how the interface between C and C++ is performed.
  375. */
  376. static void TaskFunctionAdapter(void *pvParameters);
  377. #if (INCLUDE_vTaskDelayUntil == 1)
  378. /**
  379. * Flag denoting if we've setup delay until yet.
  380. */
  381. bool delayUntilInitialized;
  382. /**
  383. * Book keeping value for delay until.
  384. */
  385. TickType_t delayUntilPreviousWakeTime;
  386. #endif
  387. #ifdef CPP_FREERTOS_CONDITION_VARIABLES
  388. /**
  389. * How we wait and signal the thread when using condition variables.
  390. * Because a semaphore maintains state, this solves the race
  391. * condition between dropping the CvLock and waiting.
  392. */
  393. BinarySemaphore ThreadWaitSem;
  394. /**
  395. * Internal helper function to signal this thread.
  396. */
  397. inline void Signal()
  398. {
  399. ThreadWaitSem.Give();
  400. }
  401. /**
  402. * The Thread class and the ConditionVariable class are interdependent.
  403. * If we allow the ConditionVariable class to access the internals of
  404. * the Thread class, we can reduce the public interface, which is a
  405. * good thing.
  406. */
  407. friend class ConditionVariable;
  408. #endif
  409. };
  410. }
  411. #endif