xbmc
Lockables.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 namespace XbmcThreads
12 {
13 
36  template<class L> class CountingLockable
37  {
38  friend class ConditionVariable;
39 
40  CountingLockable(const CountingLockable&) = delete;
41  CountingLockable& operator=(const CountingLockable&) = delete;
42  protected:
43  L mutex;
44  unsigned int count = 0;
45 
46  public:
47  inline CountingLockable() = default;
48 
49  // STL Lockable concept
50  inline void lock() { mutex.lock(); count++; }
51  inline bool try_lock() { return mutex.try_lock() ? count++, true : false; }
52  inline void unlock() { count--; mutex.unlock(); }
53 
58  inline bool IsLocked() const { return count > 0; }
59 
63  inline unsigned int exit(unsigned int leave = 0)
64  {
65  // it's possible we don't actually own the lock
66  // so we will try it.
67  unsigned int ret = 0;
68  if (try_lock())
69  {
70  if (leave < (count - 1))
71  {
72  ret = count - 1 - leave; // The -1 is because we don't want
73  // to count the try_lock increment.
74  // We must NOT compare "count" in this loop since
75  // as soon as the last unlock is called another thread
76  // can modify it.
77  for (unsigned int i = 0; i < ret; i++)
78  unlock();
79  }
80  unlock(); // undo the try_lock before returning
81  }
82 
83  return ret;
84  }
85 
89  inline void restore(unsigned int restoreCount)
90  {
91  for (unsigned int i = 0; i < restoreCount; i++)
92  lock();
93  }
94 
104  inline L& get_underlying() { return mutex; }
105  };
106 
107 }
This template will take any implementation of the "Lockable" concept and allow it to be used as an "E...
Definition: Lockables.h:36
void restore(unsigned int restoreCount)
Restore a previous exit to the provided level.
Definition: Lockables.h:89
This is a thin wrapper around std::condition_variable_any.
Definition: Condition.h:26
L & get_underlying()
Some implementations (see pthreads) require access to the underlying CCriticalSection, which is also implementation specific.
Definition: Lockables.h:104
unsigned int exit(unsigned int leave=0)
This implements the "exitable" behavior mentioned above.
Definition: Lockables.h:63
bool IsLocked() const
Check if have a lock owned.
Definition: Lockables.h:58
Definition: RecursiveMutex.cpp:11