xbmc
SharedSection.h
1 /*
2  * Copyright (C) 2005-2018 Team Kodi
3  * This file is part of Kodi - https://kodi.tv
4  *
5  * SPDX-License-Identifier: GPL-2.0-or-later
6  * See LICENSES/README.md for more information.
7  */
8 
9 #pragma once
10 
11 #include "threads/Condition.h"
12 
13 #include <mutex>
14 #include <shared_mutex>
15 
20 {
21  CCriticalSection sec;
23 
24  unsigned int sharedCount = 0;
25 
26 public:
27  inline CSharedSection() = default;
28 
29  inline void lock()
30  {
31  std::unique_lock<CCriticalSection> l(sec);
32  while (sharedCount)
33  actualCv.wait(l, [this]() { return sharedCount == 0; });
34  sec.lock();
35  }
36  inline bool try_lock() { return (sec.try_lock() ? ((sharedCount == 0) ? true : (sec.unlock(), false)) : false); }
37  inline void unlock() { sec.unlock(); }
38 
39  inline void lock_shared()
40  {
41  std::unique_lock<CCriticalSection> l(sec);
42  sharedCount++;
43  }
44  inline bool try_lock_shared() { return (sec.try_lock() ? sharedCount++, sec.unlock(), true : false); }
45  inline void unlock_shared()
46  {
47  std::unique_lock<CCriticalSection> l(sec);
48  sharedCount--;
49  if (!sharedCount)
50  {
51  actualCv.notifyAll();
52  }
53  }
54 };
This is a thin wrapper around std::condition_variable_any.
Definition: Condition.h:26
A CSharedSection is a mutex that satisfies the Shared Lockable concept (see Lockables.h).
Definition: SharedSection.h:19