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  Copyright (C) 2014 by Andreas Lauser
5 
6  This file is part of the Open Porous Media project (OPM).
7 
8  OPM is free software: you can redistribute it and/or modify
9  it under the terms of the GNU General Public License as published by
10  the Free Software Foundation, either version 2 of the License, or
11  (at your option) any later version.
12 
13  OPM is distributed in the hope that it will be useful,
14  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  GNU General Public License for more details.
17 
18  You should have received a copy of the GNU General Public License
19  along with OPM. If not, see <http://www.gnu.org/licenses/>.
20 */
26 #ifndef EWOMS_LOCKS_HH
27 #define EWOMS_LOCKS_HH
28 
29 #if defined(_OPENMP) || DOXYGEN
30 #include <omp.h>
31 
35 class OmpMutex
36 {
37 public:
38  OmpMutex() { omp_init_lock(&lock_); }
39  ~OmpMutex() { omp_destroy_lock(&lock_); }
40  void lock() { omp_set_lock(&lock_); }
41  void unlock() { omp_unset_lock(&lock_); }
42 
43  OmpMutex(const OmpMutex&) { omp_init_lock(&lock_); }
44  OmpMutex& operator= (const OmpMutex&) { return *this; }
45 
46 private:
47  omp_lock_t lock_;
48 };
49 #else
50 /* A dummy mutex that doesn't actually exclude anything,
51  * but as there is no parallelism either, no worries. */
52 class OmpMutex
53 {
54 public:
55  void lock() {}
56  void unlock() {}
57 };
58 #endif
59 
64 {
65 public:
66  explicit ScopedLock(OmpMutex& m)
67  : mutex_(m)
68  , isLocked_(true)
69  { mutex_.lock(); }
70 
72  { unlock(); }
73 
74  void operator=(const ScopedLock&) = delete;
75  ScopedLock(const ScopedLock&) = delete;
76 
77  void unlock()
78  {
79  if (!isLocked_)
80  return;
81  isLocked_ = false;
82  mutex_.unlock();
83 
84  }
85 
86  void lockAgain()
87  {
88  if(isLocked_)
89  return;
90  mutex_.lock();
91  isLocked_ = true;
92  }
93 
94 private:
95  OmpMutex& mutex_;
96  bool isLocked_;
97 };
98 
99 #endif
OmpMutex & operator=(const OmpMutex &)
Definition: locks.hh:44
OmpMutex()
Definition: locks.hh:38
void unlock()
Definition: locks.hh:77
void lock()
Definition: locks.hh:40
void unlock()
Definition: locks.hh:41
void operator=(const ScopedLock &)=delete
This class implements an exception-safe scoped lock-keeper.
Definition: locks.hh:63
~ScopedLock()
Definition: locks.hh:71
~OmpMutex()
Definition: locks.hh:39
ScopedLock(OmpMutex &m)
Definition: locks.hh:66
Implements a shallow wrapper around the "raw" locks provided by OpenMP.
Definition: locks.hh:35
void lockAgain()
Definition: locks.hh:86
OmpMutex(const OmpMutex &)
Definition: locks.hh:43