Merge pull request #26278 from basilgello/taglib2-fix-piers
[xbmc.git] / xbmc / threads / SharedSection.h
blobdce371d3b25b0ba4e8b8540d192bb463df69fb7b
1 /*
2 * Copyright (C) 2005-2018 Team Kodi
3 * This file is part of Kodi - https://kodi.tv
5 * SPDX-License-Identifier: GPL-2.0-or-later
6 * See LICENSES/README.md for more information.
7 */
9 #pragma once
11 #include "threads/Condition.h"
13 #include <mutex>
14 #include <shared_mutex>
16 /**
17 * A CSharedSection is a mutex that satisfies the Shared Lockable concept (see Lockables.h).
19 class CSharedSection
21 CCriticalSection sec;
22 XbmcThreads::ConditionVariable actualCv;
24 unsigned int sharedCount = 0;
26 public:
27 inline CSharedSection() = default;
29 inline void lock()
31 std::unique_lock<CCriticalSection> l(sec);
32 while (sharedCount)
33 actualCv.wait(l, [this]() { return sharedCount == 0; });
34 sec.lock();
36 inline bool try_lock() { return (sec.try_lock() ? ((sharedCount == 0) ? true : (sec.unlock(), false)) : false); }
37 inline void unlock() { sec.unlock(); }
39 inline void lock_shared()
41 std::unique_lock<CCriticalSection> l(sec);
42 sharedCount++;
44 inline bool try_lock_shared() { return (sec.try_lock() ? sharedCount++, sec.unlock(), true : false); }
45 inline void unlock_shared()
47 std::unique_lock<CCriticalSection> l(sec);
48 sharedCount--;
49 if (!sharedCount)
51 actualCv.notifyAll();