mutex_sample.c 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. /*
  2. * Copyright (c) 2006-2018, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2018-08-24 yangjie the first version
  9. * 2020-10-17 Meco Man translate to English comment
  10. */
  11. /*
  12. * Demo: mutex(es)
  13. *
  14. * This demo demonstrates how the mutex manage the shared resource.
  15. *
  16. * read more:
  17. * https://www.rt-thread.io/document/site/thread-sync/thread-sync/#mutex
  18. */
  19. #include <rtthread.h>
  20. #define THREAD_PRIORITY 8
  21. #define THREAD_TIMESLICE 5
  22. /* mutex handler */
  23. static rt_mutex_t dynamic_mutex = RT_NULL;
  24. static rt_uint8_t number1, number2 = 0;
  25. ALIGN(RT_ALIGN_SIZE)
  26. static char thread1_stack[1024];
  27. static struct rt_thread thread1;
  28. static void rt_thread_entry1(void *parameter)
  29. {
  30. while (1)
  31. {
  32. /* pending the mutex */
  33. rt_mutex_take(dynamic_mutex, RT_WAITING_FOREVER);
  34. /* protect and deal with public variables */
  35. number1++;
  36. rt_thread_mdelay(10);
  37. number2++;
  38. /* release the mutex */
  39. rt_mutex_release(dynamic_mutex);
  40. }
  41. }
  42. ALIGN(RT_ALIGN_SIZE)
  43. static char thread2_stack[1024];
  44. static struct rt_thread thread2;
  45. static void rt_thread_entry2(void *parameter)
  46. {
  47. while (1)
  48. {
  49. rt_mutex_take(dynamic_mutex, RT_WAITING_FOREVER);
  50. if (number1 != number2)
  51. {
  52. rt_kprintf("not protect.number1 = %d, mumber2 = %d \n", number1, number2);
  53. }
  54. else
  55. {
  56. rt_kprintf("mutex protect ,number1 = mumber2 is %d\n", number1);
  57. }
  58. number1++;
  59. number2++;
  60. rt_mutex_release(dynamic_mutex);
  61. if (number1 >= 50)
  62. return;
  63. }
  64. }
  65. int mutex_sample(void)
  66. {
  67. /* create mutex */
  68. dynamic_mutex = rt_mutex_create("dmutex", RT_IPC_FLAG_FIFO);
  69. if (dynamic_mutex == RT_NULL)
  70. {
  71. rt_kprintf("create dynamic mutex failed.\n");
  72. return -1;
  73. }
  74. rt_thread_init(&thread1,
  75. "thread1",
  76. rt_thread_entry1,
  77. RT_NULL,
  78. &thread1_stack[0],
  79. sizeof(thread1_stack),
  80. THREAD_PRIORITY, THREAD_TIMESLICE);
  81. rt_thread_startup(&thread1);
  82. rt_thread_init(&thread2,
  83. "thread2",
  84. rt_thread_entry2,
  85. RT_NULL,
  86. &thread2_stack[0],
  87. sizeof(thread2_stack),
  88. THREAD_PRIORITY - 1, THREAD_TIMESLICE);
  89. rt_thread_startup(&thread2);
  90. return 0;
  91. }
  92. /* export the msh command */
  93. MSH_CMD_EXPORT(mutex_sample, mutex sample);