1 // Copyright (C) 2014 The Android Open Source Project
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
7 // http://www.apache.org/licenses/LICENSE-2.0
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.
15 #include "emugl/common/thread.h"
17 #include "emugl/common/mutex.h"
19 #include <gtest/gtest.h>
25 // A simple thread instance that does nothing at all and exits immediately.
26 class EmptyThread : public ::emugl::Thread {
28 intptr_t main() { return 42; }
31 class CountingThread : public ::emugl::Thread {
35 State() : mLock(), mCount(0) {}
57 CountingThread(State* state) : mState(state) {}
68 class WaitingThread : public ::emugl::Thread {
70 WaitingThread(Mutex* lock) : mLock(lock) {}
73 // Try to acquire lock.
76 // Then try to release it.
86 TEST(ThreadTest, WaitForSimpleThread) {
87 Thread* thread = new EmptyThread();
89 EXPECT_TRUE(thread->start());
91 EXPECT_TRUE(thread->wait(&status));
92 EXPECT_EQ(42, status);
95 TEST(ThreadTest, WaitForMultipleThreads) {
96 CountingThread::State state;
97 const size_t kMaxThreads = 100;
98 Thread* threads[kMaxThreads];
100 // Create all threads.
101 for (size_t n = 0; n < kMaxThreads; ++n) {
102 threads[n] = new CountingThread(&state);
103 EXPECT_TRUE(threads[n]) << "thread " << n;
107 for (size_t n = 0; n < kMaxThreads; ++n) {
108 EXPECT_TRUE(threads[n]->start()) << "thread " << n;
111 // Wait for them all.
112 for (size_t n = 0; n < kMaxThreads; ++n) {
113 EXPECT_TRUE(threads[n]->wait(NULL)) << "thread " << n;
117 EXPECT_EQ((int)kMaxThreads, state.count());
120 for (size_t n = 0; n < kMaxThreads; ++n) {
125 TEST(ThreadTest, TryWaitForMultipleThreads) {
127 const size_t kMaxThreads = 100;
128 Thread* threads[kMaxThreads];
130 // Create all threads.
131 for (size_t n = 0; n < kMaxThreads; ++n) {
132 threads[n] = new WaitingThread(&lock);
133 EXPECT_TRUE(threads[n]) << "thread " << n;
136 // Acquire the lock, this will block all threads.
140 for (size_t n = 0; n < kMaxThreads; ++n) {
141 EXPECT_TRUE(threads[n]->start()) << "thread " << n;
144 // Check that tryWait() fails for all threads.
145 for (size_t n = 0; n < kMaxThreads; ++n) {
146 EXPECT_FALSE(threads[n]->tryWait(NULL)) << "thread" << n;
149 // Release the lock, this will unblock all threads.
152 // Wait for them all.
153 for (size_t n = 0; n < kMaxThreads; ++n) {
154 EXPECT_TRUE(threads[n]->wait(NULL)) << "thread " << n;
155 EXPECT_TRUE(threads[n]->tryWait(NULL)) << "thread " << n;
159 for (size_t n = 0; n < kMaxThreads; ++n) {