1
/****************************************************************************
3
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
4
** Contact: http://www.qt-project.org/legal
6
** This file is part of the QtCore module of the Qt Toolkit.
8
** $QT_BEGIN_LICENSE:LGPL$
9
** Commercial License Usage
10
** Licensees holding valid commercial Qt licenses may use this file in
11
** accordance with the commercial license agreement provided with the
12
** Software or, alternatively, in accordance with the terms contained in
13
** a written agreement between you and Digia. For licensing terms and
14
** conditions see http://qt.digia.com/licensing. For further information
15
** use the contact form at http://qt.digia.com/contact-us.
17
** GNU Lesser General Public License Usage
18
** Alternatively, this file may be used under the terms of the GNU Lesser
19
** General Public License version 2.1 as published by the Free Software
20
** Foundation and appearing in the file LICENSE.LGPL included in the
21
** packaging of this file. Please review the following information to
22
** ensure the GNU Lesser General Public License version 2.1 requirements
23
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
25
** In addition, as a special exception, Digia gives you certain additional
26
** rights. These rights are described in the Digia Qt LGPL Exception
27
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
29
** GNU General Public License Usage
30
** Alternatively, this file may be used under the terms of the GNU
31
** General Public License version 3.0 as published by the Free Software
32
** Foundation and appearing in the file LICENSE.GPL included in the
33
** packaging of this file. Please review the following information to
34
** ensure the GNU General Public License version 3.0 requirements will be
35
** met: http://www.gnu.org/copyleft/gpl.html.
40
****************************************************************************/
42
#include "qplatformdefs.h"
43
#include "qreadwritelock.h"
48
#include "qwaitcondition.h"
50
#include "qreadwritelock_p.h"
54
/*! \class QReadWriteLock
56
\brief The QReadWriteLock class provides read-write locking.
62
A read-write lock is a synchronization tool for protecting
63
resources that can be accessed for reading and writing. This type
64
of lock is useful if you want to allow multiple threads to have
65
simultaneous read-only access, but as soon as one thread wants to
66
write to the resource, all other threads must be blocked until
67
the writing is complete.
69
In many cases, QReadWriteLock is a direct competitor to QMutex.
70
QReadWriteLock is a good choice if there are many concurrent
71
reads and writing occurs infrequently.
75
\snippet code/src_corelib_thread_qreadwritelock.cpp 0
77
To ensure that writers aren't blocked forever by readers, readers
78
attempting to obtain a lock will not succeed if there is a blocked
79
writer waiting for access, even if the lock is currently only
80
accessed by other readers. Also, if the lock is accessed by a
81
writer and another writer comes in, that writer will have
82
priority over any readers that might also be waiting.
84
Like QMutex, a QReadWriteLock can be recursively locked by the
85
same thread when constructed with \l{QReadWriteLock::Recursive} as
86
\l{QReadWriteLock::RecursionMode}. In such cases,
87
unlock() must be called the same number of times lockForWrite() or
88
lockForRead() was called. Note that the lock type cannot be
89
changed when trying to lock recursively, i.e. it is not possible
90
to lock for reading in a thread that already has locked for
91
writing (and vice versa).
93
\sa QReadLocker, QWriteLocker, QMutex, QSemaphore
97
\enum QReadWriteLock::RecursionMode
100
\value Recursive In this mode, a thread can lock the same
101
QReadWriteLock multiple times and the mutex won't be unlocked
102
until a corresponding number of unlock() calls have been made.
104
\value NonRecursive In this mode, a thread may only lock a
113
Constructs a QReadWriteLock object in the given \a recursionMode.
115
The default recursion mode is NonRecursive.
117
\sa lockForRead(), lockForWrite(), RecursionMode
119
QReadWriteLock::QReadWriteLock(RecursionMode recursionMode)
120
: d(new QReadWriteLockPrivate(recursionMode))
124
Destroys the QReadWriteLock object.
126
\warning Destroying a read-write lock that is in use may result
127
in undefined behavior.
129
QReadWriteLock::~QReadWriteLock()
135
Locks the lock for reading. This function will block the current
136
thread if another thread has locked for writing.
138
It is not possible to lock for read if the thread already has
141
\sa unlock(), lockForWrite(), tryLockForRead()
143
void QReadWriteLock::lockForRead()
145
QMutexLocker lock(&d->mutex);
149
self = QThread::currentThreadId();
151
QHash<Qt::HANDLE, int>::iterator it = d->currentReaders.find(self);
152
if (it != d->currentReaders.end()) {
155
Q_ASSERT_X(d->accessCount > 0, "QReadWriteLock::lockForRead()",
156
"Overflow in lock counter");
161
while (d->accessCount < 0 || d->waitingWriters) {
163
d->readerWait.wait(&d->mutex);
167
d->currentReaders.insert(self, 1);
170
Q_ASSERT_X(d->accessCount > 0, "QReadWriteLock::lockForRead()", "Overflow in lock counter");
174
Attempts to lock for reading. If the lock was obtained, this
175
function returns true, otherwise it returns false instead of
176
waiting for the lock to become available, i.e. it does not block.
178
The lock attempt will fail if another thread has locked for
181
If the lock was obtained, the lock must be unlocked with unlock()
182
before another thread can successfully lock it for writing.
184
It is not possible to lock for read if the thread already has
187
\sa unlock(), lockForRead()
189
bool QReadWriteLock::tryLockForRead()
191
QMutexLocker lock(&d->mutex);
195
self = QThread::currentThreadId();
197
QHash<Qt::HANDLE, int>::iterator it = d->currentReaders.find(self);
198
if (it != d->currentReaders.end()) {
201
Q_ASSERT_X(d->accessCount > 0, "QReadWriteLock::tryLockForRead()",
202
"Overflow in lock counter");
207
if (d->accessCount < 0)
210
d->currentReaders.insert(self, 1);
213
Q_ASSERT_X(d->accessCount > 0, "QReadWriteLock::tryLockForRead()", "Overflow in lock counter");
220
Attempts to lock for reading. This function returns true if the
221
lock was obtained; otherwise it returns false. If another thread
222
has locked for writing, this function will wait for at most \a
223
timeout milliseconds for the lock to become available.
225
Note: Passing a negative number as the \a timeout is equivalent to
226
calling lockForRead(), i.e. this function will wait forever until
227
lock can be locked for reading when \a timeout is negative.
229
If the lock was obtained, the lock must be unlocked with unlock()
230
before another thread can successfully lock it for writing.
232
It is not possible to lock for read if the thread already has
235
\sa unlock(), lockForRead()
237
bool QReadWriteLock::tryLockForRead(int timeout)
239
QMutexLocker lock(&d->mutex);
243
self = QThread::currentThreadId();
245
QHash<Qt::HANDLE, int>::iterator it = d->currentReaders.find(self);
246
if (it != d->currentReaders.end()) {
249
Q_ASSERT_X(d->accessCount > 0, "QReadWriteLock::tryLockForRead()",
250
"Overflow in lock counter");
255
while (d->accessCount < 0 || d->waitingWriters) {
257
bool success = d->readerWait.wait(&d->mutex, timeout < 0 ? ULONG_MAX : ulong(timeout));
263
d->currentReaders.insert(self, 1);
266
Q_ASSERT_X(d->accessCount > 0, "QReadWriteLock::tryLockForRead()", "Overflow in lock counter");
272
Locks the lock for writing. This function will block the current
273
thread if another thread (including the current) has locked for
274
reading or writing (unless the lock has been created using the
275
\l{QReadWriteLock::Recursive} mode).
277
It is not possible to lock for write if the thread already has
280
\sa unlock(), lockForRead(), tryLockForWrite()
282
void QReadWriteLock::lockForWrite()
284
QMutexLocker lock(&d->mutex);
288
self = QThread::currentThreadId();
290
if (d->currentWriter == self) {
292
Q_ASSERT_X(d->accessCount < 0, "QReadWriteLock::lockForWrite()",
293
"Overflow in lock counter");
298
while (d->accessCount != 0) {
300
d->writerWait.wait(&d->mutex);
304
d->currentWriter = self;
307
Q_ASSERT_X(d->accessCount < 0, "QReadWriteLock::lockForWrite()", "Overflow in lock counter");
311
Attempts to lock for writing. If the lock was obtained, this
312
function returns true; otherwise, it returns false immediately.
314
The lock attempt will fail if another thread has locked for
317
If the lock was obtained, the lock must be unlocked with unlock()
318
before another thread can successfully lock it.
320
It is not possible to lock for write if the thread already has
323
\sa unlock(), lockForWrite()
325
bool QReadWriteLock::tryLockForWrite()
327
QMutexLocker lock(&d->mutex);
331
self = QThread::currentThreadId();
333
if (d->currentWriter == self) {
335
Q_ASSERT_X(d->accessCount < 0, "QReadWriteLock::lockForWrite()",
336
"Overflow in lock counter");
341
if (d->accessCount != 0)
344
d->currentWriter = self;
347
Q_ASSERT_X(d->accessCount < 0, "QReadWriteLock::tryLockForWrite()",
348
"Overflow in lock counter");
355
Attempts to lock for writing. This function returns true if the
356
lock was obtained; otherwise it returns false. If another thread
357
has locked for reading or writing, this function will wait for at
358
most \a timeout milliseconds for the lock to become available.
360
Note: Passing a negative number as the \a timeout is equivalent to
361
calling lockForWrite(), i.e. this function will wait forever until
362
lock can be locked for writing when \a timeout is negative.
364
If the lock was obtained, the lock must be unlocked with unlock()
365
before another thread can successfully lock it.
367
It is not possible to lock for write if the thread already has
370
\sa unlock(), lockForWrite()
372
bool QReadWriteLock::tryLockForWrite(int timeout)
374
QMutexLocker lock(&d->mutex);
378
self = QThread::currentThreadId();
380
if (d->currentWriter == self) {
382
Q_ASSERT_X(d->accessCount < 0, "QReadWriteLock::lockForWrite()",
383
"Overflow in lock counter");
388
while (d->accessCount != 0) {
390
bool success = d->writerWait.wait(&d->mutex, timeout < 0 ? ULONG_MAX : ulong(timeout));
397
d->currentWriter = self;
400
Q_ASSERT_X(d->accessCount < 0, "QReadWriteLock::tryLockForWrite()",
401
"Overflow in lock counter");
409
Attempting to unlock a lock that is not locked is an error, and will result
410
in program termination.
412
\sa lockForRead(), lockForWrite(), tryLockForRead(), tryLockForWrite()
414
void QReadWriteLock::unlock()
416
QMutexLocker lock(&d->mutex);
418
Q_ASSERT_X(d->accessCount != 0, "QReadWriteLock::unlock()", "Cannot unlock an unlocked lock");
420
bool unlocked = false;
421
if (d->accessCount > 0) {
422
// releasing a read lock
424
Qt::HANDLE self = QThread::currentThreadId();
425
QHash<Qt::HANDLE, int>::iterator it = d->currentReaders.find(self);
426
if (it != d->currentReaders.end()) {
427
if (--it.value() <= 0)
428
d->currentReaders.erase(it);
432
unlocked = --d->accessCount == 0;
433
} else if (d->accessCount < 0 && ++d->accessCount == 0) {
434
// released a write lock
436
d->currentWriter = 0;
440
if (d->waitingWriters) {
441
d->writerWait.wakeOne();
442
} else if (d->waitingReaders) {
443
d->readerWait.wakeAll();
451
\brief The QReadLocker class is a convenience class that
452
simplifies locking and unlocking read-write locks for read access.
458
The purpose of QReadLocker (and QWriteLocker) is to simplify
459
QReadWriteLock locking and unlocking. Locking and unlocking
460
statements or in exception handling code is error-prone and
461
difficult to debug. QReadLocker can be used in such situations
462
to ensure that the state of the lock is always well-defined.
464
Here's an example that uses QReadLocker to lock and unlock a
465
read-write lock for reading:
467
\snippet code/src_corelib_thread_qreadwritelock.cpp 1
469
It is equivalent to the following code:
471
\snippet code/src_corelib_thread_qreadwritelock.cpp 2
473
The QMutexLocker documentation shows examples where the use of a
474
locker object greatly simplifies programming.
476
\sa QWriteLocker, QReadWriteLock
480
\fn QReadLocker::QReadLocker(QReadWriteLock *lock)
482
Constructs a QReadLocker and locks \a lock for reading. The lock
483
will be unlocked when the QReadLocker is destroyed. If \c lock is
484
zero, QReadLocker does nothing.
486
\sa QReadWriteLock::lockForRead()
490
\fn QReadLocker::~QReadLocker()
492
Destroys the QReadLocker and unlocks the lock that was passed to
495
\sa QReadWriteLock::unlock()
499
\fn void QReadLocker::unlock()
501
Unlocks the lock associated with this locker.
503
\sa QReadWriteLock::unlock()
507
\fn void QReadLocker::relock()
509
Relocks an unlocked lock.
515
\fn QReadWriteLock *QReadLocker::readWriteLock() const
517
Returns a pointer to the read-write lock that was passed
524
\brief The QWriteLocker class is a convenience class that
525
simplifies locking and unlocking read-write locks for write access.
531
The purpose of QWriteLocker (and QReadLocker) is to simplify
532
QReadWriteLock locking and unlocking. Locking and unlocking
533
statements or in exception handling code is error-prone and
534
difficult to debug. QWriteLocker can be used in such situations
535
to ensure that the state of the lock is always well-defined.
537
Here's an example that uses QWriteLocker to lock and unlock a
538
read-write lock for writing:
540
\snippet code/src_corelib_thread_qreadwritelock.cpp 3
542
It is equivalent to the following code:
544
\snippet code/src_corelib_thread_qreadwritelock.cpp 4
546
The QMutexLocker documentation shows examples where the use of a
547
locker object greatly simplifies programming.
549
\sa QReadLocker, QReadWriteLock
553
\fn QWriteLocker::QWriteLocker(QReadWriteLock *lock)
555
Constructs a QWriteLocker and locks \a lock for writing. The lock
556
will be unlocked when the QWriteLocker is destroyed. If \c lock is
557
zero, QWriteLocker does nothing.
559
\sa QReadWriteLock::lockForWrite()
563
\fn QWriteLocker::~QWriteLocker()
565
Destroys the QWriteLocker and unlocks the lock that was passed to
568
\sa QReadWriteLock::unlock()
572
\fn void QWriteLocker::unlock()
574
Unlocks the lock associated with this locker.
576
\sa QReadWriteLock::unlock()
580
\fn void QWriteLocker::relock()
582
Relocks an unlocked lock.
588
\fn QReadWriteLock *QWriteLocker::readWriteLock() const
590
Returns a pointer to the read-write lock that was passed
596
#endif // QT_NO_THREAD