Skip to content

Commit 9908a8d

Browse files
committed
[utest][cpp]add cpp-mutex testcase.
1 parent 34b98d9 commit 9908a8d

File tree

1 file changed

+124
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)