ManaPlus
mutex.h
Go to the documentation of this file.
1 /*
2  * The ManaPlus Client
3  * Copyright (C) 2008-2009 The Mana World Development Team
4  * Copyright (C) 2009-2010 The Mana Developers
5  * Copyright (C) 2011-2019 The ManaPlus Developers
6  * Copyright (C) 2019-2021 Andrei Karas
7  *
8  * This file is part of The ManaPlus Client.
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program. If not, see <http://www.gnu.org/licenses/>.
22  */
23 
24 #ifndef UTILS_MUTEX_H
25 #define UTILS_MUTEX_H
26 
27 #include "logger.h"
28 
33 class Mutex final
34 {
35  public:
36  Mutex();
37 
39 
40  ~Mutex();
41 
42  void lock();
43 
44  void unlock();
45 
46  private:
47 // Mutex(const Mutex&); // prevent copying
48 // Mutex& operator=(const Mutex&);
49 
50  SDL_mutex *mMutex;
51 };
52 
57 {
58  public:
59  explicit MutexLocker(Mutex *const mutex);
60 
62  mMutex(m.mMutex)
63  {
64  }
65 
67 
68  ~MutexLocker();
69 
70  private:
72 };
73 
74 
75 inline Mutex::Mutex() :
76  mMutex(SDL_CreateMutex())
77 {
78 }
79 
80 inline Mutex::~Mutex()
81 {
82  SDL_DestroyMutex(mMutex);
83 }
84 
85 inline void Mutex::lock()
86 {
87  if (SDL_mutexP(mMutex) == -1)
88  logger->log("Mutex locking failed: %s", SDL_GetError());
89 }
90 
91 inline void Mutex::unlock()
92 {
93  if (SDL_mutexV(mMutex) == -1)
94  logger->log("Mutex unlocking failed: %s", SDL_GetError());
95 }
96 
97 
98 inline MutexLocker::MutexLocker(Mutex *const mutex) :
99  mMutex(mutex)
100 {
101  if (mMutex != nullptr)
102  mMutex->lock();
103 }
104 
106 {
107  if (mMutex != nullptr)
108  mMutex->unlock();
109 }
110 
111 #endif // UTILS_MUTEX_H
void log(const char *const log_text,...)
Definition: logger.cpp:269
Mutex * mMutex
Definition: mutex.h:71
~MutexLocker()
Definition: mutex.h:105
MutexLocker(const MutexLocker &m)
Definition: mutex.h:61
MutexLocker(Mutex *const mutex)
Definition: mutex.h:98
Definition: mutex.h:34
void unlock()
Definition: mutex.h:91
Mutex()
Definition: mutex.h:75
SDL_mutex * mMutex
Definition: mutex.h:50
~Mutex()
Definition: mutex.h:80
void lock()
Definition: mutex.h:85
#define final
Definition: localconsts.h:46
#define A_DELETE_COPY(func)
Definition: localconsts.h:53
#define A_DEFAULT_COPY(func)
Definition: localconsts.h:41
Logger * logger
Definition: logger.cpp:89