CPPMyth
Library to interoperate with MythTV server
Loading...
Searching...
No Matches
mutex.h
1#pragma once
2/*
3 * Copyright (C) 2015 Jean-Luc Barriere
4 *
5 * This library is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU Lesser General Public License as published
7 * by the Free Software Foundation; either version 3, or (at your option)
8 * any later version.
9 *
10 * This library 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 Lesser General Public License for more details.
14 *
15 * You should have received a copy of the GNU Lesser General Public License
16 * along with this library; see the file COPYING. If not, write to
17 * the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston,
18 * MA 02110-1301 USA
19 * http://www.gnu.org/copyleft/gpl.html
20 *
21 */
22
23#include "os-threads.h"
24
25#ifdef NSROOT
26namespace NSROOT {
27#endif
28namespace OS
29{
30
31 class Mutex
32 {
33 public:
34 Mutex()
35 : m_lockCount(0)
36 {
37 mutex_init(&m_handle);
38 }
39
40 ~Mutex()
41 {
42 clear();
43 mutex_destroy(&m_handle);
44 }
45
46 mutex_t* native_handle()
47 {
48 return &m_handle;
49 }
50
51 bool try_lock()
52 {
53 if (mutex_trylock(&m_handle))
54 {
55 ++m_lockCount;
56 return true;
57 }
58 return false;
59 }
60
61 void lock()
62 {
63 mutex_lock(&m_handle);
64 ++m_lockCount;
65 }
66
67 void unlock()
68 {
69 if (mutex_trylock(&m_handle))
70 {
71 if (m_lockCount > 0)
72 {
73 --m_lockCount;
74 mutex_unlock(&m_handle);
75 }
76 mutex_unlock(&m_handle);
77 }
78 }
79
80 void clear()
81 {
82 if (mutex_trylock(&m_handle))
83 {
84 for (unsigned i = m_lockCount; i > 0; --i)
85 mutex_unlock(&m_handle);
86 m_lockCount = 0;
87 mutex_unlock(&m_handle);
88 }
89 }
90
91 // Prevent copy
92 Mutex(const Mutex& other) = delete;
93 Mutex& operator=(const Mutex& other) = delete;
94
95 private:
96 mutex_t m_handle;
97 unsigned m_lockCount;
98 };
99
100 class LockGuard
101 {
102 public:
103 LockGuard(Mutex& mutex) : m_mutex(mutex) { m_mutex.lock(); }
104 ~LockGuard() { m_mutex.unlock(); }
105
106 // Prevent copy
107 LockGuard(const LockGuard& other) = delete;
108 LockGuard& operator=(const LockGuard& other) = delete;
109
110 private:
111 Mutex& m_mutex;
112 };
113
114}
115#ifdef NSROOT
116}
117#endif