GCC Code Coverage Report
Directory: src/ Exec Total Coverage
File: src/utils/mutex.h Lines: 17 19 89.5 %
Date: 2021-03-17 Branches: 11 38 28.9 %

Line Branch Exec Source
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
29
/**
30
 * A mutex provides mutual exclusion of access to certain data that is
31
 * accessed by multiple threads.
32
 */
33
class Mutex final
34
{
35
    public:
36
        Mutex();
37
38
        A_DELETE_COPY(Mutex)
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
53
/**
54
 * A convenience class for locking a mutex.
55
 */
56
class MutexLocker final
57
{
58
    public:
59
        explicit MutexLocker(Mutex *const mutex);
60
61
        MutexLocker(const MutexLocker &m) :
62
            mMutex(m.mMutex)
63
        {
64
        }
65
66
        A_DEFAULT_COPY(MutexLocker)
67
68
        ~MutexLocker();
69
70
    private:
71
        Mutex *mMutex;
72
};
73
74
75
3
inline Mutex::Mutex() :
76
3
    mMutex(SDL_CreateMutex())
77
{
78
}
79
80
3
inline Mutex::~Mutex()
81
{
82
3
    SDL_DestroyMutex(mMutex);
83
}
84
85
51
inline void Mutex::lock()
86
{
87
51
    if (SDL_mutexP(mMutex) == -1)
88
        logger->log("Mutex locking failed: %s", SDL_GetError());
89
51
}
90
91
51
inline void Mutex::unlock()
92
{
93
51
    if (SDL_mutexV(mMutex) == -1)
94
        logger->log("Mutex unlocking failed: %s", SDL_GetError());
95
51
}
96
97
98
15
inline MutexLocker::MutexLocker(Mutex *const mutex) :
99
51
    mMutex(mutex)
100
{
101



51
    if (mMutex != nullptr)
102
51
        mMutex->lock();
103
}
104
105
51
inline MutexLocker::~MutexLocker()
106
{
107




51
    if (mMutex != nullptr)
108
51
        mMutex->unlock();
109
}
110
111
#endif  // UTILS_MUTEX_H