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 <pthread.h>
20
21 struct CondVarTestData {
22 int variable;
23 pthread_mutex_t mutex;
24 pthread_cond_t cond;
25 };
26
ThreadCondVarFunc(void * arg)27 void* ThreadCondVarFunc(void* arg) {
28 CondVarTestData* data = reinterpret_cast<CondVarTestData*>(arg);
29 pthread_mutex_lock(&data->mutex);
30 data->variable = 1;
31 pthread_cond_broadcast(&data->cond);
32 pthread_mutex_unlock(&data->mutex);
33 return nullptr;
34 }
35
TEST(CondVar,Init)36 TEST(CondVar, Init) {
37 pthread_condattr_t attr;
38 pthread_cond_t cond;
39 ASSERT_EQ(pthread_condattr_init(&attr), 0);
40 ASSERT_EQ(pthread_cond_init(&cond, &attr), 0);
41 ASSERT_EQ(pthread_cond_destroy(&cond), 0);
42 ASSERT_EQ(pthread_condattr_destroy(&attr), 0);
43 }
44
TEST(CondVar,Synchronize)45 TEST(CondVar, Synchronize) {
46 pthread_t thread;
47 CondVarTestData data = {0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER};
48 ASSERT_EQ(pthread_mutex_lock(&data.mutex), 0);
49 // Hold mutex to ensure that broadcast is called after wait.
50 ASSERT_EQ(pthread_create(&thread, nullptr, ThreadCondVarFunc, reinterpret_cast<void*>(&data)), 0);
51 do {
52 ASSERT_EQ(pthread_cond_wait(&data.cond, &data.mutex), 0);
53 } while (data.variable == 0);
54 ASSERT_EQ(pthread_mutex_unlock(&data.mutex), 0);
55 ASSERT_EQ(pthread_cond_destroy(&data.cond), 0);
56 ASSERT_EQ(pthread_mutex_destroy(&data.mutex), 0);
57 ASSERT_EQ(pthread_join(thread, nullptr), 0);
58 ASSERT_EQ(data.variable, 1);
59 }
60