1 /**
2 * Copyright (c) 2021-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 <pthread.h>
17 #include <cstdlib>
18 #define MC_ON
19 #include "unix/libpandabase/futex/fmutex.cpp"
20
21 // The tests checks work with two mutexes
22
23 pthread_t pthread_self(void);
24 // Copy of mutex storage, after complete implementation should totally replace mutex::current_tid
25 thread_local pthread_t current_tid;
26
27 static struct fmutex g_x;
28 static struct fmutex g_y;
29 static int g_shared;
30
Thread1(void *arg)31 static void *Thread1(void *arg)
32 {
33 intptr_t index = reinterpret_cast<intptr_t>(arg);
34
35 bool ret;
36 MutexLock(&g_x, false);
37 MutexLock(&g_y, false);
38 g_shared = index;
39 int r = g_shared;
40 ASSERT(r == index);
41 MutexUnlock(&g_y);
42 MutexUnlock(&g_x);
43 return 0;
44 }
45
Thread2(void *arg)46 static void *Thread2(void *arg)
47 {
48 intptr_t index = reinterpret_cast<intptr_t>(arg);
49
50 bool ret;
51 MutexLock(&g_x, false);
52 g_shared = index;
53 int r = g_shared;
54 ASSERT(r == index);
55 MutexUnlock(&g_x);
56 return 0;
57 }
58
Thread3(void *arg)59 static void *Thread3(void *arg)
60 {
61 intptr_t index = reinterpret_cast<intptr_t>(arg);
62
63 bool ret;
64 MutexLock(&g_y, false);
65 g_shared = index;
66 int r = g_shared;
67 ASSERT(r == index);
68 MutexUnlock(&g_y);
69 return 0;
70 }
71
main()72 int main()
73 {
74 constexpr int N = 3;
75 MutexInit(&g_x);
76 MutexInit(&g_y);
77 pthread_t t[N];
78
79 pthread_create(&t[1U], nullptr, Thread2, reinterpret_cast<void *>(1U));
80 pthread_create(&t[0U], nullptr, Thread1, reinterpret_cast<void *>(0U));
81 pthread_join(t[1U], nullptr);
82 pthread_create(&t[2U], nullptr, Thread3, reinterpret_cast<void *>(2U));
83
84 pthread_join(t[0U], nullptr);
85 pthread_join(t[2U], nullptr);
86
87 MutexDestroy(&g_x);
88 MutexDestroy(&g_y);
89 return 0;
90 }
91