File: foregroundlock.cpp

package info (click to toggle)
kdevelop 4%3A5.6.2-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 57,892 kB
  • sloc: cpp: 278,773; javascript: 3,558; python: 3,385; sh: 1,317; ansic: 689; xml: 273; php: 95; makefile: 40; lisp: 13; sed: 12
file content (246 lines) | stat: -rw-r--r-- 7,046 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
/*
    Copyright 2010 David Nolden <david.nolden.kdevelop@art-master.de>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

*/

#include "foregroundlock.h"

#include <QApplication>
#include <QMutex>
#include <QThread>

using namespace KDevelop;

namespace {

QMutex internalMutex;
QMutex tryLockMutex;
QMutex waitMutex;
QMutex finishMutex;
QWaitCondition condition;

volatile QThread* holderThread = nullptr;
volatile int recursion = 0;

void lockForegroundMutexInternal()
{
    if (holderThread == QThread::currentThread()) {
        // We already have the mutex
        ++recursion;
    } else {
        internalMutex.lock();
        Q_ASSERT(recursion == 0 && holderThread == nullptr);
        holderThread = QThread::currentThread();
        recursion = 1;
    }
}

bool tryLockForegroundMutexInternal(int interval = 0)
{
    if (holderThread == QThread::currentThread()) {
        // We already have the mutex
        ++recursion;
        return true;
    } else {
        if (internalMutex.tryLock(interval)) {
            Q_ASSERT(recursion == 0 && holderThread == nullptr);
            holderThread = QThread::currentThread();
            recursion = 1;
            return true;
        } else {
            return false;
        }
    }
}

void unlockForegroundMutexInternal(bool duringDestruction = false)
{
    /// Note: QThread::currentThread() might already be invalid during destruction.
    if (!duringDestruction) {
        Q_ASSERT(holderThread == QThread::currentThread());
    }

    Q_ASSERT(recursion > 0);
    recursion -= 1;
    if (recursion == 0) {
        holderThread = nullptr;
        internalMutex.unlock();
    }
}
}

ForegroundLock::ForegroundLock(bool lock)
{
    if (lock)
        relock();
}

void KDevelop::ForegroundLock::relock()
{
    Q_ASSERT(!m_locked);

    if (!QApplication::instance() || // Initialization isn't complete yet
        QThread::currentThread() == QApplication::instance()->thread() || // We're the main thread (deadlock might happen if we'd enter the trylock loop)
        holderThread == QThread::currentThread()) { // We already have the foreground lock (deadlock might happen if we'd enter the trylock loop)
        lockForegroundMutexInternal();
    } else {
        QMutexLocker lock(&tryLockMutex);

        while (!tryLockForegroundMutexInternal(10)) {
            // In case an additional event-loop was started from within the foreground, we send
            // events to the foreground to temporarily release the lock.

            class ForegroundReleaser : public DoInForeground
            {
public:
                void doInternal() override
                {
                    // By locking the mutex, we make sure that the requester is actually waiting for the condition
                    waitMutex.lock();
                    // Now we release the foreground lock
                    TemporarilyReleaseForegroundLock release;
                    // And signalize to the requester that we've released it
                    condition.wakeAll();
                    // Allow the requester to actually wake up, by unlocking m_waitMutex
                    waitMutex.unlock();
                    // Now wait until the requester is ready
                    QMutexLocker lock(&finishMutex);
                }
            };

            static ForegroundReleaser releaser;

            QMutexLocker lockWait(&waitMutex);
            QMutexLocker lockFinish(&finishMutex);

            QMetaObject::invokeMethod(&releaser, "doInternalSlot", Qt::QueuedConnection);
            // We limit the waiting time here, because sometimes it may happen that the foreground-lock is released,
            // and the foreground is waiting without an event-loop running. (For example through TemporarilyReleaseForegroundLock)
            condition.wait(&waitMutex, 30);

            if (tryLockForegroundMutexInternal()) {
                //success
                break;
            } else {
                //Probably a third thread has creeped in and
                //got the foreground lock before us. Just try again.
            }
        }
    }
    m_locked = true;
    Q_ASSERT(holderThread == QThread::currentThread());
    Q_ASSERT(recursion > 0);
}

bool KDevelop::ForegroundLock::isLockedForThread()
{
    return QThread::currentThread() == holderThread ||
           QThread::currentThread() == QApplication::instance()->thread();
}

bool KDevelop::ForegroundLock::tryLock()
{
    if (tryLockForegroundMutexInternal()) {
        m_locked = true;
        return true;
    }
    return false;
}

void KDevelop::ForegroundLock::unlock()
{
    Q_ASSERT(m_locked);
    unlockForegroundMutexInternal();
    m_locked = false;
}

TemporarilyReleaseForegroundLock::TemporarilyReleaseForegroundLock()
{
    Q_ASSERT(holderThread == QThread::currentThread());

    m_recursion = 0;

    while (holderThread == QThread::currentThread()) {
        unlockForegroundMutexInternal();
        ++m_recursion;
    }
}

TemporarilyReleaseForegroundLock::~TemporarilyReleaseForegroundLock()
{
    for (int a = 0; a < m_recursion; ++a)
        lockForegroundMutexInternal();

    Q_ASSERT(recursion == m_recursion && holderThread == QThread::currentThread());
}

KDevelop::ForegroundLock::~ForegroundLock()
{
    if (m_locked)
        unlock();
}

bool KDevelop::ForegroundLock::isLocked() const
{
    return m_locked;
}

namespace KDevelop {
void DoInForeground::doIt()
{
    if (QThread::currentThread() == QApplication::instance()->thread()) {
        // We're already in the foreground, just call the handler code
        doInternal();
    } else {
        QMutexLocker lock(&m_mutex);
        QMetaObject::invokeMethod(this, "doInternalSlot", Qt::QueuedConnection);
        m_wait.wait(&m_mutex);
    }
}

DoInForeground::~DoInForeground()
{
}

DoInForeground::DoInForeground()
{
    moveToThread(QApplication::instance()->thread());
}

void DoInForeground::doInternalSlot()
{
    VERIFY_FOREGROUND_LOCKED
        doInternal();
    QMutexLocker lock(&m_mutex);
    m_wait.wakeAll();
}
}

// Important: The foreground lock has to be held by default, so lock it during static initialization
static struct StaticLock
{
    StaticLock()
    {
        lockForegroundMutexInternal();
    }
    ~StaticLock()
    {
        unlockForegroundMutexInternal(true);
    }
private:
    Q_DISABLE_COPY(StaticLock)
} staticLock;