Subversion Repositories tpanel

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
447 andreas 1
/*
2
 * Copyright (C) 2023 by Andreas Theofilu <andreas@theosys.at>
3
 *
4
 * This program is free software; you can redistribute it and/or modify
5
 * it under the terms of the GNU General Public License as published by
6
 * the Free Software Foundation; either version 3 of the License, or
7
 * (at your option) any later version.
8
 *
9
 * This program 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
12
 * GNU General Public License for more details.
13
 *
14
 * You should have received a copy of the GNU General Public License
15
 * along with this program; if not, write to the Free Software Foundation,
16
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
17
 */
18
 
19
#ifndef __TLOCK_H__
20
#define __TLOCK_H__
21
 
22
#include <string>
23
#include <mutex>
24
#include <thread>
25
 
26
typedef struct __LOCKLIST_t
27
{
28
    std::mutex::native_handle_type native_handle;   // Handle of mutex
29
    bool state{false};                              // TRUE = mutex is locked
30
    bool noDeathLock{false};                        // TRUE = Ignores additional logging to prevent a death lock.
31
}__LOCKLIST_t;
32
 
33
template<typename _TMutex>
34
class TLock
35
{
36
    public:
37
        typedef _TMutex mutex_type;
38
        explicit TLock(mutex_type& __m);
39
        explicit TLock(mutex_type& __m, char *file, int line);
40
        explicit TLock(mutex_type& __m, bool tryit, char *file, int line);
41
        TLock(mutex_type& __m, std::adopt_lock_t) noexcept;
42
        ~TLock();
43
 
44
        void unlock();
45
        void unlock(char *file, int line);
46
        void relock();
47
        bool isLocked();
48
        void setNoDeathLock(bool l);     // USE WITH CARE!! This disables locking for the mutex!!
49
        void _setMetaData(char *file, int line) { mFilename = file; mLineNumber = line; }
50
 
51
        TLock(const TLock&) = delete;
52
        TLock& operator=(const TLock&) = delete;
53
 
54
    private:
55
        bool addLock(bool *death=nullptr);
56
        void wait();
57
        bool removeLock();
58
        void stripFileName();
59
 
60
        mutex_type&  _M_device;
61
        bool mNoDeathLock{false};
62
        std::string mFilename;
63
        int mLineNumber{0};
64
};
65
 
66
#include "tlock.cc"
67
 
68
#define TLOCKER(mtx)    TLock<std::mutex> __Guard(mtx, (char *)__FILE__, __LINE__)
69
#define TUNLOCKER()     __Guard.unlock((char *)__FILE__, __LINE__)
70
#define TTRYLOCK(mtx)   TLock<std::mutex> __Guard(mtx, true, (char *)__FILE__, __LINE__)
71
 
72
#endif