Skip to content

Commit d848e73

Browse files
committed
[utest][cpp]add cpp-mutex testcase.
1 parent a4e5ae7 commit d848e73

File tree

1 file changed

+120
-0
lines changed

1 file changed

+120
-0
lines changed
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
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+
11+
#include <rtthread.h>
12+
#include "utest.h"
13+
#include <thread>
14+
#include <mutex>
15+
#include <chrono>
16+
17+
/**
18+
* @brief Test basic mutex operations with lock_guard.
19+
*/
20+
static void test_mutex(void)
21+
{
22+
std::mutex m;
23+
int count = 0;
24+
auto func = [&]() mutable {
25+
std::lock_guard<std::mutex> lock(m);
26+
for (int i = 0; i < 1000; ++i)
27+
{
28+
++count;
29+
}
30+
};
31+
32+
std::thread t1(func);
33+
std::thread t2(func);
34+
35+
t1.join();
36+
t2.join();
37+
38+
uassert_int_equal(count, 2000);
39+
}
40+
41+
/**
42+
* @brief Test recursive mutex allowing multiple locks by the same thread.
43+
*/
44+
static void test_recursive_mutex(void)
45+
{
46+
std::recursive_mutex rm;
47+
int count = 0;
48+
auto func = [&]() mutable {
49+
std::lock_guard<std::recursive_mutex> lock1(rm);
50+
std::lock_guard<std::recursive_mutex> lock2(rm);
51+
for (int i = 0; i < 1000; ++i)
52+
{
53+
++count;
54+
}
55+
};
56+
57+
std::thread t1(func);
58+
std::thread t2(func);
59+
60+
t1.join();
61+
t2.join();
62+
63+
if (count != 2000)
64+
{
65+
uassert_false(true);
66+
}
67+
uassert_true(true);
68+
}
69+
70+
/**
71+
* @brief Test try_lock on mutex.
72+
*/
73+
static void test_try_lock(void)
74+
{
75+
std::mutex m;
76+
if (m.try_lock())
77+
{
78+
m.unlock();
79+
uassert_true(true);
80+
}
81+
else
82+
{
83+
uassert_false(true);
84+
}
85+
}
86+
87+
/**
88+
* @brief Test locking multiple mutexes with std::lock.
89+
*/
90+
static void test_lock_multiple(void)
91+
{
92+
std::mutex m1, m2;
93+
std::lock(m1, m2);
94+
m1.unlock();
95+
m2.unlock();
96+
uassert_true(true);
97+
}
98+
99+
static rt_err_t utest_tc_init(void)
100+
{
101+
return RT_EOK;
102+
}
103+
104+
static rt_err_t utest_tc_cleanup(void)
105+
{
106+
return RT_EOK;
107+
}
108+
109+
static void testcase(void)
110+
{
111+
/* Test basic mutex operations with lock_guard */
112+
UTEST_UNIT_RUN(test_mutex);
113+
/* Test recursive mutex allowing multiple locks by the same thread */
114+
UTEST_UNIT_RUN(test_recursive_mutex);
115+
/* Test try_lock on mutex */
116+
UTEST_UNIT_RUN(test_try_lock);
117+
/* Test locking multiple mutexes with std::lock */
118+
UTEST_UNIT_RUN(test_lock_multiple);
119+
}
120+
UTEST_TC_EXPORT(testcase, "testcases.cpp11.mutex_tc", utest_tc_init, utest_tc_cleanup, 10);

0 commit comments

Comments
 (0)