platform_thread.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. * @Author: jiejie
  3. * @Github: https://github.com/jiejieTop
  4. * @Date: 2019-12-23 19:26:27
  5. * @LastEditTime: 2020-02-23 16:19:07
  6. * @Description: the code belongs to jiejie, please keep the author information and source code according to the license.
  7. */
  8. #include "platform_thread.h"
  9. #include "platform_memory.h"
  10. platform_thread_t *platform_thread_init( const char *name,
  11. void (*entry)(void *),
  12. void * const param,
  13. unsigned int stack_size,
  14. unsigned int priority,
  15. unsigned int tick)
  16. {
  17. int res;
  18. platform_thread_t *thread;
  19. void *(*thread_entry) (void *);
  20. thread_entry = (void *(*)(void*))entry;
  21. thread = platform_memory_alloc(sizeof(platform_thread_t));
  22. if (NULL == thread) {
  23. return NULL;
  24. }
  25. // 修复竞态条件:在创建线程之前先初始化 mutex 和 cond
  26. // 否则新线程可能在这些成员初始化之前就开始访问它们
  27. thread->mutex = (pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER;
  28. thread->cond = (pthread_cond_t)PTHREAD_COND_INITIALIZER;
  29. // 现在才创建线程,此时 mutex 和 cond 已经初始化完成
  30. res = pthread_create(&thread->thread, NULL, thread_entry, param);
  31. if(res != 0) {
  32. platform_memory_free(thread);
  33. return NULL;
  34. }
  35. return thread;
  36. }
  37. void platform_thread_startup(platform_thread_t* thread)
  38. {
  39. (void) thread;
  40. }
  41. void platform_thread_stop(platform_thread_t* thread)
  42. {
  43. // 添加 NULL 检查,防止空指针解引用
  44. if (NULL == thread) {
  45. return;
  46. }
  47. pthread_mutex_lock(&(thread->mutex));
  48. pthread_cond_wait(&(thread->cond), &(thread->mutex));
  49. pthread_mutex_unlock(&(thread->mutex));
  50. }
  51. void platform_thread_start(platform_thread_t* thread)
  52. {
  53. // 添加 NULL 检查,防止空指针解引用
  54. if (NULL == thread) {
  55. return;
  56. }
  57. pthread_mutex_lock(&(thread->mutex));
  58. pthread_cond_signal(&(thread->cond));
  59. pthread_mutex_unlock(&(thread->mutex));
  60. }
  61. void platform_thread_destroy(platform_thread_t* thread)
  62. {
  63. if (NULL != thread)
  64. pthread_detach(thread->thread);
  65. }