MPD  0.20.18
DatabaseLock.hxx
Go to the documentation of this file.
1 /*
2  * Copyright 2003-2017 The Music Player Daemon Project
3  * http://www.musicpd.org
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18  */
19 
26 #ifndef MPD_DB_LOCK_HXX
27 #define MPD_DB_LOCK_HXX
28 
29 #include "check.h"
30 #include "thread/Mutex.hxx"
31 #include "Compiler.h"
32 
33 #include <assert.h>
34 
35 extern Mutex db_mutex;
36 
37 #ifndef NDEBUG
38 
39 #include "thread/Id.hxx"
40 
42 
47 static inline bool
48 holding_db_lock() noexcept
49 {
50  return db_mutex_holder.IsInside();
51 }
52 
53 #endif
54 
59 static inline void
60 db_lock(void)
61 {
62  assert(!holding_db_lock());
63 
64  db_mutex.lock();
65 
66  assert(db_mutex_holder.IsNull());
67 #ifndef NDEBUG
68  db_mutex_holder = ThreadId::GetCurrent();
69 #endif
70 }
71 
75 static inline void
76 db_unlock(void)
77 {
78  assert(holding_db_lock());
79 #ifndef NDEBUG
80  db_mutex_holder = ThreadId::Null();
81 #endif
82 
83  db_mutex.unlock();
84 }
85 
87  bool locked = true;
88 
89 public:
91  db_lock();
92  }
93 
95  if (locked)
96  db_unlock();
97  }
98 
102  void unlock() {
103  assert(locked);
104 
105  db_unlock();
106  locked = false;
107  }
108 };
109 
114 public:
116  db_unlock();
117  }
118 
120  db_lock();
121  }
122 };
123 
124 #endif
static gcc_pure bool holding_db_lock() noexcept
Does the current thread hold the database lock?
static constexpr ThreadId Null() noexcept
Definition: Id.hxx:55
A low-level identification for a thread.
Definition: Id.hxx:36
Definition: Mutex.hxx:43
static void db_unlock(void)
Release the global database lock.
bool IsInside() const noexcept
Check if this thread is the current thread.
Definition: Id.hxx:94
gcc_pure bool IsNull() const noexcept
Definition: Id.hxx:64
Unlock the database while in the current scope.
Mutex db_mutex
void unlock()
Definition: PosixMutex.hxx:71
static void db_lock(void)
Obtain the global database lock.
ThreadId db_mutex_holder
static gcc_pure const ThreadId GetCurrent() noexcept
Return the current thread's id .
Definition: Id.hxx:72
void unlock()
Unlock the mutex now, making the destructor a no-op.
#define gcc_pure
Definition: Compiler.h:116
void lock()
Definition: PosixMutex.hxx:63