timeslice_sample.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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_STACK_SIZE 1024
  18. #define THREAD_PRIORITY 20
  19. #define THREAD_TIMESLICE 10
  20. /* 线程入口 */
  21. static void thread_entry(void *parameter)
  22. {
  23. rt_uint32_t value;
  24. rt_uint32_t count = 0;
  25. value = (rt_uint32_t)parameter;
  26. while (1)
  27. {
  28. if (0 == (count % 5))
  29. {
  30. rt_kprintf("thread %d is running ,thread %d count = %d\n", value, value, count);
  31. if (count > 200)
  32. return;
  33. }
  34. count++;
  35. }
  36. }
  37. int timeslice_sample(void)
  38. {
  39. rt_thread_t tid = RT_NULL;
  40. /* 创建线程1 */
  41. tid = rt_thread_create("thread1",
  42. thread_entry, (void *)1,
  43. THREAD_STACK_SIZE,
  44. THREAD_PRIORITY, THREAD_TIMESLICE);
  45. #ifdef RT_USING_SMP
  46. /* 绑定线程到同一个核上,避免启用多核时的输出混乱 */
  47. rt_thread_control(tid, RT_THREAD_CTRL_BIND_CPU, (void*)0);
  48. #endif
  49. if (tid != RT_NULL)
  50. rt_thread_startup(tid);
  51. /* 创建线程2 */
  52. tid = rt_thread_create("thread2",
  53. thread_entry, (void *)2,
  54. THREAD_STACK_SIZE,
  55. THREAD_PRIORITY, THREAD_TIMESLICE - 5);
  56. #ifdef RT_USING_SMP
  57. /* 绑定线程到同一个核上,避免启用多核时的输出混乱 */
  58. rt_thread_control(tid, RT_THREAD_CTRL_BIND_CPU, (void*)0);
  59. #endif
  60. if (tid != RT_NULL)
  61. rt_thread_startup(tid);
  62. return 0;
  63. }
  64. /* 导出到 msh 命令列表中 */
  65. MSH_CMD_EXPORT(timeslice_sample, timeslice sample);