interrupt_sample.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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: interrupt
  13. *
  14. * This demo demonstrates how to disable and enable interrupt to access global variable.
  15. *
  16. * read more:
  17. * https://www.rt-thread.io/document/site/programming-manual/interrupt/interrupt/
  18. */
  19. #include <rthw.h>
  20. #include <rtthread.h>
  21. #define THREAD_PRIORITY 20
  22. #define THREAD_STACK_SIZE 512
  23. #define THREAD_TIMESLICE 5
  24. /* global variable */
  25. static volatile rt_uint32_t cnt;
  26. /* thread entry function */
  27. /* threads #1 and #2 share one entry, but the entry parameter is different */
  28. static void thread_entry(void *parameter)
  29. {
  30. rt_uint32_t no;
  31. rt_uint32_t level;
  32. no = (rt_uint32_t) parameter;
  33. while (1)
  34. {
  35. /* disable interrupt */
  36. level = rt_hw_interrupt_disable();
  37. cnt += no; /* critical sections (or critical region) */
  38. /* enable interrupt */
  39. rt_hw_interrupt_enable(level);
  40. rt_kprintf("protect thread[%d]'s counter is %d\n", no, cnt);
  41. rt_thread_mdelay(no * 10);
  42. }
  43. }
  44. int interrupt_sample(void)
  45. {
  46. rt_thread_t thread;
  47. /* create thread #1 */
  48. thread = rt_thread_create("thread1", thread_entry, (void *)10,
  49. THREAD_STACK_SIZE,
  50. THREAD_PRIORITY, THREAD_TIMESLICE);
  51. #ifdef RT_USING_SMP
  52. /* Bind threads to the same core to avoid messy log output when multiple cores are enabled */
  53. rt_thread_control(thread, RT_THREAD_CTRL_BIND_CPU, (void*)0);
  54. #endif
  55. if (thread != RT_NULL)
  56. rt_thread_startup(thread); /* start thread #1 */
  57. /* create thread #2 */
  58. thread = rt_thread_create("thread2", thread_entry, (void *)20,
  59. THREAD_STACK_SIZE,
  60. THREAD_PRIORITY, THREAD_TIMESLICE);
  61. #ifdef RT_USING_SMP
  62. /* Bind threads to the same core to avoid messy log output when multiple cores are enabled */
  63. rt_thread_control(thread, RT_THREAD_CTRL_BIND_CPU, (void*)0);
  64. #endif
  65. if (thread != RT_NULL)
  66. rt_thread_startup(thread); /* start thread #2 */
  67. return 0;
  68. }
  69. /* export the msh command */
  70. MSH_CMD_EXPORT(interrupt_sample, interrupt sample);