smp_spinlock_tc.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /*
  2. * Copyright (c) 2006-2024, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2024-08-13 RV the first version
  9. */
  10. #include <rtthread.h>
  11. #include "utest.h"
  12. #include <interrupt.h>
  13. /**
  14. * @brief Spinlock testcase.
  15. *
  16. * @note Create multiple threads and use spinlocks to protect shared memory
  17. */
  18. #define THREAD_PRIORITY 20
  19. #define THREAD_TIMESLICE 20
  20. #define THREAD_STACK_SIZE UTEST_THR_STACK_SIZE
  21. static rt_thread_t thread1;
  22. static rt_thread_t thread2;
  23. static rt_uint8_t finsh_flag = 0;
  24. static struct rt_spinlock lock;
  25. static rt_uint8_t number1, number2 = 0;
  26. static void rt_thread_entry1(void *parameter)
  27. {
  28. while (1)
  29. {
  30. rt_spin_lock(&lock);
  31. number1++;
  32. rt_thread_yield();
  33. number2++;
  34. rt_spin_unlock(&lock);
  35. rt_thread_delay(5);
  36. }
  37. }
  38. static void rt_thread_entry2(void *parameter)
  39. {
  40. while (1)
  41. {
  42. rt_spin_lock(&lock);
  43. uassert_int_equal(number1, number2);
  44. number1++;
  45. number2++;
  46. rt_spin_unlock(&lock);
  47. if (number1 >= 10)
  48. {
  49. finsh_flag = 1;
  50. }
  51. rt_thread_delay(5);
  52. }
  53. }
  54. static void smp_spinlock_tc(void)
  55. {
  56. thread1 = rt_thread_create("T1", rt_thread_entry1, RT_NULL, THREAD_STACK_SIZE, THREAD_PRIORITY, 20);
  57. if (thread1 != RT_NULL)
  58. {
  59. rt_thread_startup(thread1);
  60. }
  61. thread2 = rt_thread_create("T2", rt_thread_entry2, RT_NULL, THREAD_STACK_SIZE, THREAD_PRIORITY - 1, 20);
  62. if (thread2 != RT_NULL)
  63. {
  64. rt_thread_startup(thread2);
  65. }
  66. while (finsh_flag == 0);
  67. }
  68. static rt_err_t utest_tc_init(void)
  69. {
  70. rt_spin_lock_init(&lock);
  71. return RT_EOK;
  72. }
  73. static rt_err_t utest_tc_cleanup(void)
  74. {
  75. rt_thread_delete(thread1);
  76. rt_thread_delete(thread2);
  77. return RT_EOK;
  78. }
  79. static void testcase(void)
  80. {
  81. UTEST_UNIT_RUN(smp_spinlock_tc);
  82. }
  83. UTEST_TC_EXPORT(testcase, "testcases.smp.spinlock_tc", utest_tc_init, utest_tc_cleanup, 10);