timeslice_sample.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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: 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/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. if (tid != RT_NULL)
  50. rt_thread_startup(tid); /* start thread #1 */
  51. /* create thread #2 */
  52. tid = rt_thread_create("thread2",
  53. thread_entry, (void *)2,
  54. THREAD_STACK_SIZE,
  55. THREAD_PRIORITY, THREAD_TIMESLICE - 5);
  56. if (tid != RT_NULL)
  57. rt_thread_startup(tid); /* start thread #2 */
  58. return 0;
  59. }
  60. /* export the msh command */
  61. MSH_CMD_EXPORT(timeslice_sample, timeslice sample);