locks.hh
Go to the documentation of this file.
1 // -*- mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 // vi: set et ts=4 sw=4 sts=4:
3 /*
4  This file is part of the Open Porous Media project (OPM).
5 
6  OPM is free software: you can redistribute it and/or modify
7  it under the terms of the GNU General Public License as published by
8  the Free Software Foundation, either version 2 of the License, or
9  (at your option) any later version.
10 
11  OPM is distributed in the hope that it will be useful,
12  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  GNU General Public License for more details.
15 
16  You should have received a copy of the GNU General Public License
17  along with OPM. If not, see <http://www.gnu.org/licenses/>.
18 
19  Consult the COPYING file in the top-level source directory of this
20  module for the precise wording of the license and the list of
21  copyright holders.
22 */
28 #ifndef EWOMS_LOCKS_HH
29 #define EWOMS_LOCKS_HH
30 
31 #if defined(_OPENMP) || DOXYGEN
32 #include <omp.h>
33 
37 class OmpMutex
38 {
39 public:
40  OmpMutex() { omp_init_lock(&lock_); }
41  ~OmpMutex() { omp_destroy_lock(&lock_); }
42  void lock() { omp_set_lock(&lock_); }
43  void unlock() { omp_unset_lock(&lock_); }
44 
45  OmpMutex(const OmpMutex&) { omp_init_lock(&lock_); }
46  OmpMutex& operator= (const OmpMutex&) { return *this; }
47 
48 private:
49  omp_lock_t lock_;
50 };
51 #else
52 /* A dummy mutex that doesn't actually exclude anything,
53  * but as there is no parallelism either, no worries. */
54 class OmpMutex
55 {
56 public:
57  void lock() {}
58  void unlock() {}
59 };
60 #endif
61 
66 {
67 public:
68  explicit ScopedLock(OmpMutex& m)
69  : mutex_(m)
70  , isLocked_(true)
71  { mutex_.lock(); }
72 
73  ~ScopedLock()
74  { unlock(); }
75 
76  void operator=(const ScopedLock&) = delete;
77  ScopedLock(const ScopedLock&) = delete;
78 
79  void unlock()
80  {
81  if (!isLocked_)
82  return;
83  isLocked_ = false;
84  mutex_.unlock();
85 
86  }
87 
88  void lockAgain()
89  {
90  if(isLocked_)
91  return;
92  mutex_.lock();
93  isLocked_ = true;
94  }
95 
96 private:
97  OmpMutex& mutex_;
98  bool isLocked_;
99 };
100 
101 #endif
Definition: locks.hh:54
This class implements an exception-safe scoped lock-keeper.
Definition: locks.hh:65