• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2020 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 
15 #include <chrono>
16 
17 #include "gtest/gtest.h"
18 #include "pw_sync/mutex.h"
19 
20 namespace pw::sync {
21 namespace {
22 
23 extern "C" {
24 
25 // Functions defined in mutex_facade_test_c.c which call the API from C.
26 void pw_sync_Mutex_CallLock(pw_sync_Mutex* mutex);
27 bool pw_sync_Mutex_CallTryLock(pw_sync_Mutex* mutex);
28 void pw_sync_Mutex_CallUnlock(pw_sync_Mutex* mutex);
29 
30 }  // extern "C"
31 
32 // TODO(pwbug/291): Add real concurrency tests once we have pw::thread.
33 
TEST(Mutex,LockUnlock)34 TEST(Mutex, LockUnlock) {
35   pw::sync::Mutex mutex;
36   mutex.lock();
37   // TODO(pwbug/291): Ensure it fails to lock when already held.
38   // EXPECT_FALSE(mutex.try_lock());
39   mutex.unlock();
40 }
41 
42 Mutex static_mutex;
TEST(Mutex,LockUnlockStatic)43 TEST(Mutex, LockUnlockStatic) {
44   static_mutex.lock();
45   // TODO(pwbug/291): Ensure it fails to lock when already held.
46   // EXPECT_FALSE(static_mutex.try_lock());
47   static_mutex.unlock();
48 }
49 
TEST(Mutex,TryLockUnlock)50 TEST(Mutex, TryLockUnlock) {
51   pw::sync::Mutex mutex;
52   const bool locked = mutex.try_lock();
53   EXPECT_TRUE(locked);
54   if (locked) {
55     // TODO(pwbug/291): Ensure it fails to lock when already held.
56     // EXPECT_FALSE(mutex.try_lock());
57     mutex.unlock();
58   }
59 }
60 
TEST(Mutex,LockUnlockInC)61 TEST(Mutex, LockUnlockInC) {
62   pw::sync::Mutex mutex;
63   pw_sync_Mutex_CallLock(&mutex);
64   pw_sync_Mutex_CallUnlock(&mutex);
65 }
66 
TEST(Mutex,TryLockUnlockInC)67 TEST(Mutex, TryLockUnlockInC) {
68   pw::sync::Mutex mutex;
69   ASSERT_TRUE(pw_sync_Mutex_CallTryLock(&mutex));
70   // TODO(pwbug/291): Ensure it fails to lock when already held.
71   // EXPECT_FALSE(pw_sync_Mutex_CallTryLock(&mutex));
72   pw_sync_Mutex_CallUnlock(&mutex);
73 }
74 
75 }  // namespace
76 }  // namespace pw::sync
77