Home | History | Annotate | Download | only in lib
      1 #pragma once
      2 
      3 /*
      4  * Copyright (C) 2017 The Android Open Source Project
      5  *
      6  * Licensed under the Apache License, Version 2.0 (the "License");
      7  * you may not use this file except in compliance with the License.
      8  * You may obtain a copy of the License at
      9  *
     10  *      http://www.apache.org/licenses/LICENSE-2.0
     11  *
     12  * Unless required by applicable law or agreed to in writing, software
     13  * distributed under the License is distributed on an "AS IS" BASIS,
     14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     15  * See the License for the specific language governing permissions and
     16  * limitations under the License.
     17  */
     18 
     19 #include "common/vsoc/shm/lock.h"
     20 
     21 namespace vsoc {
     22 
     23 class RegionView;
     24 
     25 /*
     26  * Implements std::lock_guard like functionality for the vsoc locks.
     27  */
     28 
     29 template <typename Lock>
     30 class LockGuard {
     31  public:
     32   explicit LockGuard(Lock* lock) : lock_(lock) {
     33     lock_->Lock();
     34   }
     35 
     36   LockGuard(LockGuard&& o) noexcept {
     37     lock_ = o.lock_;
     38     o.lock_ = nullptr;
     39   }
     40 
     41   LockGuard(const LockGuard&) = delete;
     42   LockGuard& operator=(const LockGuard&) = delete;
     43 
     44   ~LockGuard() {
     45     if (lock_) {
     46       lock_->Unlock();
     47     }
     48   }
     49 
     50  private:
     51   Lock* lock_;
     52 };
     53 
     54 template <>
     55 class LockGuard<::vsoc::layout::GuestAndHostLock> {
     56   using Lock = ::vsoc::layout::GuestAndHostLock;
     57 
     58  public:
     59   LockGuard(Lock* lock, RegionView* region) : lock_(lock), region_(region) {
     60     lock_->Lock(region_);
     61   }
     62 
     63   LockGuard(LockGuard&& o) noexcept {
     64     lock_ = o.lock_;
     65     o.lock_ = nullptr;
     66     region_ = o.region_;
     67     o.region_ = nullptr;
     68   }
     69 
     70   LockGuard(const LockGuard&) = delete;
     71   LockGuard& operator=(const LockGuard&) = delete;
     72 
     73   ~LockGuard() {
     74     if (lock_) {
     75       lock_->Unlock(region_);
     76     }
     77   }
     78 
     79  private:
     80   Lock* lock_;
     81   RegionView* region_;
     82 };
     83 
     84 }  // namespace vsoc
     85