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 #include <semaphore.h>
22
TEST(Sem,SingleThread)23 TEST(Sem, SingleThread) {
24 sem_t sem;
25 ASSERT_EQ(sem_init(&sem, 0, 0), 0);
26 ASSERT_EQ(sem_post(&sem), 0);
27 int value;
28 ASSERT_EQ(sem_getvalue(&sem, &value), 0);
29 ASSERT_EQ(value, 1);
30 ASSERT_EQ(sem_wait(&sem), 0);
31 ASSERT_EQ(sem_trywait(&sem), -1);
32 ASSERT_EQ(errno, EAGAIN);
33 ASSERT_EQ(sem_destroy(&sem), 0);
34 }
35
SeparateThread(void * arg)36 static void* SeparateThread(void* arg) {
37 sem_post(reinterpret_cast<sem_t*>(arg));
38 return nullptr;
39 }
40
TEST(Sem,UnlockOnDifferentThread)41 TEST(Sem, UnlockOnDifferentThread) {
42 sem_t sem;
43 ASSERT_EQ(sem_init(&sem, 0, 0), 0);
44 pthread_t thread;
45 ASSERT_EQ(pthread_create(&thread, nullptr, &SeparateThread, reinterpret_cast<void*>(&sem)), 0);
46 ASSERT_EQ(sem_wait(&sem), 0);
47 ASSERT_EQ(pthread_join(thread, nullptr), 0);
48 }
49