1 /*
2 * Copyright (C) 2023 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "gtest/gtest.h"
18
19 #include <errno.h>
20 #include <pthread.h>
21
TEST(Mutex,Init)22 TEST(Mutex, Init) {
23 pthread_mutexattr_t attr;
24 pthread_mutex_t mutex;
25 ASSERT_EQ(pthread_mutexattr_init(&attr), 0);
26 ASSERT_EQ(pthread_mutex_init(&mutex, &attr), 0);
27 ASSERT_EQ(pthread_mutex_destroy(&mutex), 0);
28 ASSERT_EQ(pthread_mutexattr_destroy(&attr), 0);
29 }
30
TEST(Mutex,Lock)31 TEST(Mutex, Lock) {
32 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
33 ASSERT_EQ(pthread_mutex_lock(&mutex), 0);
34 ASSERT_EQ(pthread_mutex_trylock(&mutex), EBUSY);
35 ASSERT_EQ(pthread_mutex_unlock(&mutex), 0);
36 ASSERT_EQ(pthread_mutex_destroy(&mutex), 0);
37 }
38
TEST(Mutex,RecursiveLock)39 TEST(Mutex, RecursiveLock) {
40 // The proper name for that define is with _NP (_NP means non-portable), but old versions of
41 // Bionic use a version without the _NP suffix.
42 #ifdef PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
43 pthread_mutex_t mutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
44 #else
45 pthread_mutex_t mutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER;
46 #endif
47 ASSERT_EQ(pthread_mutex_lock(&mutex), 0);
48 ASSERT_EQ(pthread_mutex_trylock(&mutex), 0);
49 ASSERT_EQ(pthread_mutex_unlock(&mutex), 0);
50 ASSERT_EQ(pthread_mutex_unlock(&mutex), 0);
51 ASSERT_EQ(pthread_mutex_destroy(&mutex), 0);
52 }
53