thread_sample.c 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. * Copyright (c) 2006-2022, 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. */
  10. /*
  11. * 程序清单:创建、初始化/脱离线程
  12. *
  13. * 这个例子会创建两个线程,一个动态线程,一个静态线程。
  14. * 静态线程在运行完毕后自动被系统脱离,动态线程一直打印计数。
  15. */
  16. #include <rtthread.h>
  17. #define THREAD_PRIORITY 25
  18. #define THREAD_STACK_SIZE 512
  19. #define THREAD_TIMESLICE 5
  20. static rt_thread_t tid1 = RT_NULL;
  21. /* 线程1的入口函数 */
  22. static void thread1_entry(void *parameter)
  23. {
  24. rt_uint32_t count = 0;
  25. while (1)
  26. {
  27. /* 线程1采用低优先级运行,一直打印计数值 */
  28. rt_kprintf("thread1 count: %d\n", count ++);
  29. rt_thread_mdelay(500);
  30. }
  31. }
  32. #ifdef rt_align
  33. rt_align(RT_ALIGN_SIZE)
  34. #else
  35. ALIGN(RT_ALIGN_SIZE)
  36. #endif
  37. static char thread2_stack[1024];
  38. static struct rt_thread thread2;
  39. /* 线程2入口 */
  40. static void thread2_entry(void *param)
  41. {
  42. rt_uint32_t count = 0;
  43. /* 线程2拥有较高的优先级,以抢占线程1而获得执行 */
  44. for (count = 0; count < 10 ; count++)
  45. {
  46. /* 线程2打印计数值 */
  47. rt_kprintf("thread2 count: %d\n", count);
  48. }
  49. rt_kprintf("thread2 exit\n");
  50. /* 线程2运行结束后也将自动被系统脱离 */
  51. }
  52. /* 线程示例 */
  53. int thread_sample(void)
  54. {
  55. /* 创建线程1,名称是thread1,入口是thread1_entry*/
  56. tid1 = rt_thread_create("thread1",
  57. thread1_entry, RT_NULL,
  58. THREAD_STACK_SIZE,
  59. THREAD_PRIORITY, THREAD_TIMESLICE);
  60. #ifdef RT_USING_SMP
  61. /* 绑定线程到同一个核上,避免启用多核时的输出混乱 */
  62. rt_thread_control(tid1, RT_THREAD_CTRL_BIND_CPU, (void*)0);
  63. #endif
  64. /* 如果获得线程控制块,启动这个线程 */
  65. if (tid1 != RT_NULL)
  66. rt_thread_startup(tid1);
  67. /* 初始化线程2,名称是thread2,入口是thread2_entry */
  68. rt_thread_init(&thread2,
  69. "thread2",
  70. thread2_entry,
  71. RT_NULL,
  72. &thread2_stack[0],
  73. sizeof(thread2_stack),
  74. THREAD_PRIORITY - 1, THREAD_TIMESLICE);
  75. #ifdef RT_USING_SMP
  76. /* 绑定线程到同一个核上,避免启用多核时的输出混乱 */
  77. rt_thread_control(&thread2, RT_THREAD_CTRL_BIND_CPU, (void*)0);
  78. #endif
  79. rt_thread_startup(&thread2);
  80. return 0;
  81. }
  82. /* 导出到 msh 命令列表中 */
  83. MSH_CMD_EXPORT(thread_sample, thread sample);