interrupt_sample.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. * Copyright (c) 2006-2021, 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/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. if (thread != RT_NULL)
  52. rt_thread_startup(thread); /* start thread #1 */
  53. /* create thread #2 */
  54. thread = rt_thread_create("thread2", thread_entry, (void *)20,
  55. THREAD_STACK_SIZE,
  56. THREAD_PRIORITY, THREAD_TIMESLICE);
  57. if (thread != RT_NULL)
  58. rt_thread_startup(thread); /* start thread #2 */
  59. return 0;
  60. }
  61. /* export the msh command */
  62. MSH_CMD_EXPORT(interrupt_sample, interrupt sample);