interrupt_sample.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. */
  10. /* 程序清单:关闭中断进行全局变量的访问 */
  11. #include <rthw.h>
  12. #include <rtthread.h>
  13. #define THREAD_PRIORITY 20
  14. #define THREAD_STACK_SIZE 512
  15. #define THREAD_TIMESLICE 5
  16. /* 同时访问的全局变量 */
  17. static rt_uint32_t cnt;
  18. static void thread_entry(void *parameter)
  19. {
  20. rt_uint32_t no;
  21. rt_uint32_t level;
  22. no = (rt_uint32_t) parameter;
  23. while (1)
  24. {
  25. /* 关闭中断 */
  26. level = rt_hw_interrupt_disable();
  27. cnt += no;
  28. /* 恢复中断 */
  29. rt_hw_interrupt_enable(level);
  30. rt_kprintf("protect thread[%d]'s counter is %d\n", no, cnt);
  31. rt_thread_mdelay(no * 10);
  32. }
  33. }
  34. int interrupt_sample(void)
  35. {
  36. rt_thread_t thread;
  37. /* 创建thread1线程 */
  38. thread = rt_thread_create("thread1", thread_entry, (void *)10,
  39. THREAD_STACK_SIZE,
  40. THREAD_PRIORITY, THREAD_TIMESLICE);
  41. #ifdef RT_USING_SMP
  42. /* 绑定线程到同一个核上,避免启用多核时的输出混乱 */
  43. rt_thread_control(thread, RT_THREAD_CTRL_BIND_CPU, (void*)0);
  44. #endif
  45. if (thread != RT_NULL)
  46. rt_thread_startup(thread);
  47. /* 创建thread2线程 */
  48. thread = rt_thread_create("thread2", thread_entry, (void *)20,
  49. THREAD_STACK_SIZE,
  50. THREAD_PRIORITY, THREAD_TIMESLICE);
  51. #ifdef RT_USING_SMP
  52. /* 绑定线程到同一个核上,避免启用多核时的输出混乱 */
  53. rt_thread_control(thread, RT_THREAD_CTRL_BIND_CPU, (void*)0);
  54. #endif
  55. if (thread != RT_NULL)
  56. rt_thread_startup(thread);
  57. return 0;
  58. }
  59. /* 导出到 msh 命令列表中 */
  60. MSH_CMD_EXPORT(interrupt_sample, interrupt sample);