GCC Code Coverage Report
Directory: src/ Exec Total Coverage
File: src/utils/mutex.h Lines: 16 18 88.9 %
Date: 2017-11-29 Branches: 6 14 42.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-2017  The ManaPlus Developers
6
 *
7
 *  This file is part of The ManaPlus Client.
8
 *
9
 *  This program is free software; you can redistribute it and/or modify
10
 *  it under the terms of the GNU General Public License as published by
11
 *  the Free Software Foundation; either version 2 of the License, or
12
 *  any later version.
13
 *
14
 *  This program is distributed in the hope that it will be useful,
15
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 *  GNU General Public License for more details.
18
 *
19
 *  You should have received a copy of the GNU General Public License
20
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
21
 */
22
23
#ifndef UTILS_MUTEX_H
24
#define UTILS_MUTEX_H
25
26
#include "logger.h"
27
28
/**
29
 * A mutex provides mutual exclusion of access to certain data that is
30
 * accessed by multiple threads.
31
 */
32
class Mutex final
33
{
34
    public:
35
        Mutex();
36
37
        A_DELETE_COPY(Mutex)
38
39
        ~Mutex();
40
41
        void lock();
42
43
        void unlock();
44
45
    private:
46
//        Mutex(const Mutex&);  // prevent copying
47
//        Mutex& operator=(const Mutex&);
48
49
        SDL_mutex *mMutex;
50
};
51
52
/**
53
 * A convenience class for locking a mutex.
54
 */
55
class MutexLocker final
56
{
57
    public:
58
        explicit MutexLocker(Mutex *const mutex);
59
60
        MutexLocker(const MutexLocker &m) :
61
            mMutex(m.mMutex)
62
        {
63
        }
64
65
        A_DEFAULT_COPY(MutexLocker)
66
67
        ~MutexLocker();
68
69
    private:
70
        Mutex *mMutex;
71
};
72
73
74
6
inline Mutex::Mutex() :
75
6
    mMutex(SDL_CreateMutex())
76
{
77
}
78
79
6
inline Mutex::~Mutex()
80
{
81
6
    SDL_DestroyMutex(mMutex);
82
}
83
84
102
inline void Mutex::lock()
85
{
86
102
    if (SDL_mutexP(mMutex) == -1)
87
        logger->log("Mutex locking failed: %s", SDL_GetError());
88
102
}
89
90
102
inline void Mutex::unlock()
91
{
92
102
    if (SDL_mutexV(mMutex) == -1)
93
        logger->log("Mutex unlocking failed: %s", SDL_GetError());
94
102
}
95
96
97
30
inline MutexLocker::MutexLocker(Mutex *const mutex) :
98
102
    mMutex(mutex)
99
{
100
    if (mMutex != nullptr)
101
102
        mMutex->lock();
102
}
103
104
102
inline MutexLocker::~MutexLocker()
105
{
106

72
    if (mMutex != nullptr)
107
102
        mMutex->unlock();
108
}
109
110
#endif  // UTILS_MUTEX_H