1/*
2 * Copyright (C) 2013 Collabora Ltd.
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Library General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Library General Public License for more details.
13 *
14 * You should have received a copy of the GNU Library General Public License
15 * along with this library; see the file COPYING.LIB. If not, write to
16 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
17 * Boston, MA 02110-1301, USA.
18 */
19
20#ifndef GMutexLocker_h
21#define GMutexLocker_h
22
23#if USE(GLIB)
24
25#include <glib.h>
26#include <wtf/Noncopyable.h>
27
28namespace WTF {
29
30template<typename T>
31struct MutexWrapper;
32
33template<>
34struct MutexWrapper<GMutex> {
35 static void lock(GMutex* mutex)
36 {
37 g_mutex_lock(mutex);
38 }
39
40 static void unlock(GMutex* mutex)
41 {
42 g_mutex_unlock(mutex);
43 }
44};
45
46template<>
47struct MutexWrapper<GRecMutex> {
48 static void lock(GRecMutex* mutex)
49 {
50 g_rec_mutex_lock(mutex);
51 }
52
53 static void unlock(GRecMutex* mutex)
54 {
55 g_rec_mutex_unlock(mutex);
56 }
57};
58
59template<typename T>
60class GMutexLocker {
61 WTF_MAKE_NONCOPYABLE(GMutexLocker);
62public:
63 explicit GMutexLocker(T& mutex)
64 : m_mutex(mutex)
65 , m_locked(false)
66 {
67 lock();
68 }
69
70 ~GMutexLocker()
71 {
72 unlock();
73 }
74
75 void lock()
76 {
77 if (m_locked)
78 return;
79
80 MutexWrapper<T>::lock(&m_mutex);
81 m_locked = true;
82 }
83
84 void unlock()
85 {
86 if (!m_locked)
87 return;
88
89 m_locked = false;
90 MutexWrapper<T>::unlock(&m_mutex);
91 }
92
93private:
94 T& m_mutex;
95 bool m_locked;
96};
97
98} // namespace WTF
99
100#endif // USE(GLIB)
101
102#endif // GMutexLocker_h
103