tc_mutex.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. /*
  2. * Copyright (c) 2006-2025, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2025-09-19 Rbb666 the first version
  9. */
  10. #include <rtthread.h>
  11. #include "utest.h"
  12. #include <thread>
  13. #include <mutex>
  14. #include <chrono>
  15. /**
  16. * @brief Test basic mutex operations with lock_guard.
  17. */
  18. static void test_mutex(void)
  19. {
  20. std::mutex m;
  21. int count = 0;
  22. auto func = [&]() mutable {
  23. std::lock_guard<std::mutex> lock(m);
  24. for (int i = 0; i < 1000; ++i)
  25. {
  26. ++count;
  27. }
  28. };
  29. std::thread t1(func);
  30. std::thread t2(func);
  31. t1.join();
  32. t2.join();
  33. uassert_int_equal(count, 2000);
  34. }
  35. /**
  36. * @brief Test recursive mutex allowing multiple locks by the same thread.
  37. */
  38. static void test_recursive_mutex(void)
  39. {
  40. std::recursive_mutex rm;
  41. int count = 0;
  42. auto func = [&]() mutable {
  43. std::lock_guard<std::recursive_mutex> lock1(rm);
  44. std::lock_guard<std::recursive_mutex> lock2(rm);
  45. for (int i = 0; i < 1000; ++i)
  46. {
  47. ++count;
  48. }
  49. };
  50. std::thread t1(func);
  51. std::thread t2(func);
  52. t1.join();
  53. t2.join();
  54. if (count != 2000)
  55. {
  56. uassert_false(true);
  57. }
  58. uassert_true(true);
  59. }
  60. /**
  61. * @brief Test try_lock on mutex.
  62. */
  63. static void test_try_lock(void)
  64. {
  65. std::mutex m;
  66. if (m.try_lock())
  67. {
  68. m.unlock();
  69. uassert_true(true);
  70. }
  71. else
  72. {
  73. uassert_false(true);
  74. }
  75. }
  76. /**
  77. * @brief Test locking multiple mutexes with std::lock.
  78. */
  79. static void test_lock_multiple(void)
  80. {
  81. std::mutex m1, m2;
  82. std::lock(m1, m2);
  83. m1.unlock();
  84. m2.unlock();
  85. uassert_true(true);
  86. }
  87. static rt_err_t utest_tc_init(void)
  88. {
  89. return RT_EOK;
  90. }
  91. static rt_err_t utest_tc_cleanup(void)
  92. {
  93. return RT_EOK;
  94. }
  95. static void testcase(void)
  96. {
  97. /* Test basic mutex operations with lock_guard */
  98. UTEST_UNIT_RUN(test_mutex);
  99. /* Test recursive mutex allowing multiple locks by the same thread */
  100. UTEST_UNIT_RUN(test_recursive_mutex);
  101. /* Test try_lock on mutex */
  102. UTEST_UNIT_RUN(test_try_lock);
  103. /* Test locking multiple mutexes with std::lock */
  104. UTEST_UNIT_RUN(test_lock_multiple);
  105. }
  106. UTEST_TC_EXPORT(testcase, "components.libc.cpp.mutex_tc", utest_tc_init, utest_tc_cleanup, 10);