1 /*
2 * Copyright (C) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include <stdlib.h>
17 #include <threads.h>
18 #include <unistd.h>
19 #include "functionalext.h"
20
21 static mtx_t g_mtex;
22
threadfuncA(void * arg)23 int threadfuncA(void *arg)
24 {
25 int32_t ret = 0;
26 ret = mtx_lock(&g_mtex);
27 ret = mtx_trylock(&g_mtex);
28 EXPECT_EQ("mtx_lock_0100", ret, thrd_success);
29 ret = mtx_unlock(&g_mtex);
30 EXPECT_EQ("mtx_lock_0100", ret, thrd_success);
31 return 0;
32 }
33
threadfuncB(void * arg)34 int threadfuncB(void *arg)
35 {
36 int32_t ret = 0;
37 ret = mtx_lock(&g_mtex);
38 ret = mtx_trylock(&g_mtex);
39 EXPECT_EQ("mtx_lock_0200", ret, thrd_busy);
40 ret = mtx_unlock(&g_mtex);
41 EXPECT_EQ("mtx_lock_0200", ret, thrd_success);
42 return 0;
43 }
44
45 /**
46 * @tc.name : mtx_trylock_0100
47 * @tc.desc : Verify process mtx_trylock success when mtx_init second args is mtx_plain | tx_recursive.
48 * @tc.level : Level 0
49 */
mtx_trylock_0100(void)50 void mtx_trylock_0100(void)
51 {
52 int result = mtx_init(&g_mtex, mtx_plain | mtx_recursive);
53 if (result != thrd_success) {
54 t_error("%s mtx_init failed", __func__);
55 return;
56 }
57 thrd_t tid1;
58 result = thrd_create(&tid1, threadfuncA, NULL);
59 if (result != thrd_success) {
60 t_error("%s thrd_create failed", __func__);
61 return;
62 }
63 result = thrd_join(tid1, NULL);
64 if (result != thrd_success) {
65 t_error("%s thrd_join failed", __func__);
66 return;
67 }
68 }
69
70 /**
71 * @tc.name : mtx_trylock_0200
72 * @tc.desc : Verify process mtx_trylock fail when mtx_init second args is mtx_plain.
73 * @tc.level : Level 2
74 */
mtx_trylock_0200(void)75 void mtx_trylock_0200(void)
76 {
77 int result = mtx_init(&g_mtex, mtx_plain);
78 if (result != thrd_success) {
79 t_error("%s mtx_init failed", __func__);
80 return;
81 }
82 thrd_t tid2;
83 result = thrd_create(&tid2, threadfuncB, NULL);
84 if (result != thrd_success) {
85 t_error("%s thrd_create failed", __func__);
86 return;
87 }
88 result = thrd_join(tid2, NULL);
89 if (result != thrd_success) {
90 t_error("%s thrd_join failed", __func__);
91 return;
92 }
93 }
94
main(int argc,char * argv[])95 int main(int argc, char *argv[])
96 {
97 mtx_trylock_0100();
98 mtx_trylock_0200();
99 return t_status;
100 }