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.

94 lines
2.3 KiB

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