timeslice_sample.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. * 2020-10-17 Meco Man translate to English comment
  10. */
  11. /*
  12. * Demo: Time-Slicing (or Round-Robin Scheduling)
  13. *
  14. * This demo creates two threads to show how Time-Slicing works.
  15. *
  16. * read more:
  17. * https://www.rt-thread.io/document/site/programming-manual/thread/thread/#time-slice
  18. */
  19. #include <rtthread.h>
  20. #define THREAD_STACK_SIZE 1024
  21. #define THREAD_PRIORITY 20
  22. #define THREAD_TIMESLICE 10
  23. /* thread entry function */
  24. /* threads #1 and #2 share one entry, but the entry parameter is different */
  25. static void thread_entry(void *parameter)
  26. {
  27. rt_uint32_t value;
  28. rt_uint32_t count = 0;
  29. value = (rt_uint32_t)parameter;
  30. while (1)
  31. {
  32. if (0 == (count % 5))
  33. {
  34. rt_kprintf("thread %d is running ,thread %d count = %d\n", value, value, count);
  35. if (count > 200)
  36. return;
  37. }
  38. count++;
  39. }
  40. }
  41. int timeslice_sample(void)
  42. {
  43. rt_thread_t tid = RT_NULL; /* thread handle */
  44. /* create thread #1 */
  45. tid = rt_thread_create("thread1",
  46. thread_entry, (void *)1,
  47. THREAD_STACK_SIZE,
  48. THREAD_PRIORITY, THREAD_TIMESLICE);
  49. #ifdef RT_USING_SMP
  50. /* Bind threads to the same core to avoid messy log output when multiple cores are enabled */
  51. rt_thread_control(tid, RT_THREAD_CTRL_BIND_CPU, (void*)0);
  52. #endif
  53. if (tid != RT_NULL)
  54. rt_thread_startup(tid); /* start thread #1 */
  55. /* create thread #2 */
  56. tid = rt_thread_create("thread2",
  57. thread_entry, (void *)2,
  58. THREAD_STACK_SIZE,
  59. THREAD_PRIORITY, THREAD_TIMESLICE - 5);
  60. #ifdef RT_USING_SMP
  61. /* Bind threads to the same core to avoid messy log output when multiple cores are enabled */
  62. rt_thread_control(tid, RT_THREAD_CTRL_BIND_CPU, (void*)0);
  63. #endif
  64. if (tid != RT_NULL)
  65. rt_thread_startup(tid); /* start thread #2 */
  66. return 0;
  67. }
  68. /* export the msh command */
  69. MSH_CMD_EXPORT(timeslice_sample, timeslice sample);