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/mutex.h"
17 #include "emugl/common/testing/test_thread.h"
19 #include <gtest/gtest.h>
23 // Check that construction and destruction doesn't crash.
24 TEST(Mutex, ConstructionDestruction) {
28 // Check that a simple lock + unlock works.
29 TEST(Mutex, LockUnlock) {
35 // Check that AutoLock compiles and doesn't crash.
36 TEST(Mutex, AutoLock) {
38 Mutex::AutoLock lock(mutex);
41 // Wrapper class for threads. Does not use emugl::Thread intentionally.
42 // Common data type used by the following tests below.
44 ThreadParams() : mutex(), counter(0) {}
50 // This thread function uses Mutex::lock/unlock to synchronize a counter
51 // increment operation.
52 static void* threadFunction(void* param) {
53 ThreadParams* p = static_cast<ThreadParams*>(param);
61 TEST(Mutex, Synchronization) {
62 const size_t kNumThreads = 2000;
63 TestThread* threads[kNumThreads];
66 // Create and launch all threads.
67 for (size_t n = 0; n < kNumThreads; ++n) {
68 threads[n] = new TestThread(threadFunction, &p);
71 // Wait until their completion.
72 for (size_t n = 0; n < kNumThreads; ++n) {
77 EXPECT_EQ(static_cast<int>(kNumThreads), p.counter);
80 // This thread function uses a Mutex::AutoLock to protect the counter.
81 static void* threadAutoLockFunction(void* param) {
82 ThreadParams* p = static_cast<ThreadParams*>(param);
84 Mutex::AutoLock lock(p->mutex);
89 TEST(Mutex, AutoLockSynchronization) {
90 const size_t kNumThreads = 2000;
91 TestThread* threads[kNumThreads];
94 // Create and launch all threads.
95 for (size_t n = 0; n < kNumThreads; ++n) {
96 threads[n] = new TestThread(threadAutoLockFunction, &p);
99 // Wait until their completion.
100 for (size_t n = 0; n < kNumThreads; ++n) {
105 EXPECT_EQ(static_cast<int>(kNumThreads), p.counter);