thread_sample.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. */
  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. ALIGN(RT_ALIGN_SIZE)
  33. static char thread2_stack[1024];
  34. static struct rt_thread thread2;
  35. /* 线程2入口 */
  36. static void thread2_entry(void *param)
  37. {
  38. rt_uint32_t count = 0;
  39. /* 线程2拥有较高的优先级,以抢占线程1而获得执行 */
  40. for (count = 0; count < 10 ; count++)
  41. {
  42. /* 线程2打印计数值 */
  43. rt_kprintf("thread2 count: %d\n", count);
  44. }
  45. rt_kprintf("thread2 exit\n");
  46. /* 线程2运行结束后也将自动被系统脱离 */
  47. }
  48. /* 线程示例 */
  49. int thread_sample(void)
  50. {
  51. /* 创建线程1,名称是thread1,入口是thread1_entry*/
  52. tid1 = rt_thread_create("thread1",
  53. thread1_entry, RT_NULL,
  54. THREAD_STACK_SIZE,
  55. THREAD_PRIORITY, THREAD_TIMESLICE);
  56. /* 如果获得线程控制块,启动这个线程 */
  57. if (tid1 != RT_NULL)
  58. rt_thread_startup(tid1);
  59. /* 初始化线程2,名称是thread2,入口是thread2_entry */
  60. rt_thread_init(&thread2,
  61. "thread2",
  62. thread2_entry,
  63. RT_NULL,
  64. &thread2_stack[0],
  65. sizeof(thread2_stack),
  66. THREAD_PRIORITY - 1, THREAD_TIMESLICE);
  67. rt_thread_startup(&thread2);
  68. return 0;
  69. }
  70. /* 导出到 msh 命令列表中 */
  71. MSH_CMD_EXPORT(thread_sample, thread sample);