thread_sample.c 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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: thread(s)
  13. *
  14. * This demo creates two threads:
  15. * 1) create thread #1 dynamically, and delete automatically when the thread #1 finished;
  16. * 2) create thread #2 statically, and print counting numbers continuously.
  17. *
  18. * read more:
  19. * https://www.rt-thread.io/document/site/thread/thread/
  20. */
  21. #include <rtthread.h>
  22. #define THREAD_PRIORITY 25
  23. #define THREAD_STACK_SIZE 512
  24. #define THREAD_TIMESLICE 5
  25. /* thread handler */
  26. static rt_thread_t tid1 = RT_NULL;
  27. /* thread #1 entry function */
  28. static void thread1_entry(void *parameter)
  29. {
  30. rt_uint32_t count = 0;
  31. while (1)
  32. {
  33. /* thread #1 occupies low priority and prints counting numbers continuously */
  34. rt_kprintf("thread1 count: %d\n", count ++);
  35. rt_thread_mdelay(500);
  36. }
  37. }
  38. ALIGN(RT_ALIGN_SIZE)
  39. static char thread2_stack[1024];
  40. static struct rt_thread thread2;
  41. /* thread #2 entry function */
  42. static void thread2_entry(void *param)
  43. {
  44. rt_uint32_t count = 0;
  45. /* thread #2 occupies higher priority than that of thread #1 */
  46. for (count = 0; count < 10 ; count++)
  47. {
  48. /* thread #2 prints counting numbers */
  49. rt_kprintf("thread2 count: %d\n", count);
  50. }
  51. rt_kprintf("thread2 exit\n");
  52. /* RT-Thread allows thread entry function to return directly */
  53. /* thread #2 will be deleted automatically by idle thread once it finishes */
  54. }
  55. int thread_sample(void)
  56. {
  57. /* create thread #1 dynamically */
  58. tid1 = rt_thread_create("thread1",
  59. thread1_entry, RT_NULL,
  60. THREAD_STACK_SIZE,
  61. THREAD_PRIORITY, THREAD_TIMESLICE);
  62. /* start thread #1 */
  63. if (tid1 != RT_NULL)
  64. rt_thread_startup(tid1);
  65. /* create thread #2 statically */
  66. rt_thread_init(&thread2,
  67. "thread2",
  68. thread2_entry,
  69. RT_NULL,
  70. &thread2_stack[0],
  71. sizeof(thread2_stack),
  72. THREAD_PRIORITY - 1, THREAD_TIMESLICE);
  73. rt_thread_startup(&thread2); /* start thread #2 */
  74. return 0;
  75. }
  76. /* export the msh command */
  77. MSH_CMD_EXPORT(thread_sample, thread sample);