You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

100 lines
2.5 KiB

1 year ago
  1. #include "zthread.hpp"
  2. #include "mutex.hpp"
  3. #include"logger.h"
  4. using namespace iflytop;
  5. using namespace std;
  6. static bool s_map_inited = false;
  7. static ZThread g_default_thread;
  8. static void zosthread_default_task(void const *argument) {
  9. ZThread *thread = (ZThread *)argument;
  10. ZASSERT(thread);
  11. thread->threadcb();
  12. };
  13. void ZThread::zthread_module_init() {
  14. if (s_map_inited) return;
  15. s_map_inited = true;
  16. }
  17. void ZThread::threadcb() {
  18. m_status = kidle;
  19. while (true) {
  20. if (m_threadisworkingFlagCallSide) {
  21. m_status = kworking;
  22. if (m_taskfunction) m_taskfunction();
  23. if (m_taskfunction_exitcb) m_taskfunction_exitcb();
  24. m_status = kdead;
  25. while (m_threadisworkingFlagCallSide) {
  26. vTaskDelay(10);
  27. }
  28. m_status = kidle;
  29. }
  30. vTaskDelay(10);
  31. }
  32. }
  33. void ZThread::init(const char *threadname, int stack_size, osPriority priority) {
  34. // int r_task_create = 0;
  35. ZASSERT(threadname);
  36. m_lock = xSemaphoreCreateMutex();
  37. ZASSERT(m_lock);
  38. m_stacksize = stack_size;
  39. m_uxPriority = osPriorityNormal;
  40. m_taskfunction = nullptr;
  41. m_zthreadstartworkevent = xEventGroupCreate();
  42. m_name = threadname;
  43. osThreadDef(zosthread_default_task, zosthread_default_task, m_uxPriority, 0, m_stacksize);
  44. m_defaultTaskHandle = osThreadCreate(osThread(zosthread_default_task), this);
  45. ZASSERT(m_defaultTaskHandle != NULL);
  46. }
  47. void ZThread::start(zosthread_cb_t cb) { start(cb, nullptr); }
  48. void ZThread::start(zosthread_cb_t cb, zosthread_cb_t exitcb) {
  49. stop();
  50. m_taskfunction = cb;
  51. m_taskfunction_exitcb = exitcb;
  52. ZASSERT(m_taskfunction);
  53. xSemaphoreTake(m_lock, portMAX_DELAY);
  54. m_threadisworkingFlagCallSide = true;
  55. // xEventGroupSetBits(m_zthreadstartworkevent, 0x01);
  56. while (m_status == kidle) {
  57. xTaskNotifyGive(m_defaultTaskHandle);
  58. vTaskDelay(1);
  59. }
  60. xSemaphoreGive(m_lock);
  61. }
  62. void ZThread::stop() {
  63. xSemaphoreTake(m_lock, portMAX_DELAY);
  64. m_threadisworkingFlagCallSide = false;
  65. // xEventGroupSetBits(m_zthreadstartworkevent, 0x01);
  66. while (m_status != kidle) {
  67. xTaskNotifyGive(m_defaultTaskHandle);
  68. vTaskDelay(1);
  69. }
  70. xSemaphoreGive(m_lock);
  71. }
  72. void ZThread::sleep(uint32_t ms) { ulTaskNotifyTake(pdFALSE, pdMS_TO_TICKS(ms)); }
  73. void ZThread::wake() {
  74. BaseType_t state;
  75. if (xPortIsInsideInterrupt()) {
  76. vTaskNotifyGiveFromISR(m_defaultTaskHandle, &state);
  77. } else {
  78. xTaskNotifyGive(m_defaultTaskHandle);
  79. }
  80. }