• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2017 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 #include "common/vsoc/shm/lock.h"
17 
18 #include <thread>
19 #include <vector>
20 
21 #include <gtest/gtest.h>
22 
23 #include "common/vsoc/lib/region_view.h"
24 
25 #ifdef CUTTLEFISH_HOST
26 using MyLock = vsoc::layout::HostLock;
27 #else
28 using MyLock = vsoc::layout::GuestLock;
29 #endif
30 
31 class SimpleLocker {
32  public:
33   enum State {
34     BEFORE_EXECUTION,
35     BEFORE_LOCK,
36     IN_CRITICAL_SECTION,
37     DONE,
38     JOINED
39   };
40 
SimpleLocker(MyLock * lock)41   explicit SimpleLocker(MyLock* lock)
42       : lock_(lock), thread_(&SimpleLocker::Work, this) {}
43 
Work()44   void Work() {
45     state_ = BEFORE_LOCK;
46     lock_->Lock();
47     state_ = IN_CRITICAL_SECTION;
48     InCriticalSection();
49     lock_->Unlock();
50     state_ = DONE;
51   }
52 
InCriticalSection()53   void InCriticalSection() {}
54 
Join()55   void Join() {
56     thread_.join();
57     state_ = JOINED;
58   }
59 
60  protected:
61   MyLock* lock_;
62   volatile State state_{BEFORE_EXECUTION};
63   std::thread thread_;
64 };
65 
TEST(LockTest,Basic)66 TEST(LockTest, Basic) {
67   // In production regions are always 0 filled on allocation. That's not
68   // true on the stack, so initialize the lock when we declare it.
69   MyLock lock{};
70   SimpleLocker a(&lock);
71   SimpleLocker b(&lock);
72   a.Join();
73   b.Join();
74 }
75