PageRenderTime 26ms CodeModel.GetById 10ms RepoModel.GetById 1ms app.codeStats 0ms

/src/qt/qtbase/src/corelib/thread/qmutex.cpp

https://gitlab.com/x33n/phantomjs
C++ | 663 lines | 266 code | 52 blank | 345 comment | 67 complexity | 6fe53011593fc36b98c3f63109da9944 MD5 | raw file
  1. /****************************************************************************
  2. **
  3. ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
  4. ** Copyright (C) 2012 Intel Corporation
  5. ** Copyright (C) 2012 Olivier Goffart <ogoffart@woboq.com>
  6. ** Contact: http://www.qt-project.org/legal
  7. **
  8. ** This file is part of the QtCore module of the Qt Toolkit.
  9. **
  10. ** $QT_BEGIN_LICENSE:LGPL$
  11. ** Commercial License Usage
  12. ** Licensees holding valid commercial Qt licenses may use this file in
  13. ** accordance with the commercial license agreement provided with the
  14. ** Software or, alternatively, in accordance with the terms contained in
  15. ** a written agreement between you and Digia. For licensing terms and
  16. ** conditions see http://qt.digia.com/licensing. For further information
  17. ** use the contact form at http://qt.digia.com/contact-us.
  18. **
  19. ** GNU Lesser General Public License Usage
  20. ** Alternatively, this file may be used under the terms of the GNU Lesser
  21. ** General Public License version 2.1 as published by the Free Software
  22. ** Foundation and appearing in the file LICENSE.LGPL included in the
  23. ** packaging of this file. Please review the following information to
  24. ** ensure the GNU Lesser General Public License version 2.1 requirements
  25. ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
  26. **
  27. ** In addition, as a special exception, Digia gives you certain additional
  28. ** rights. These rights are described in the Digia Qt LGPL Exception
  29. ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
  30. **
  31. ** GNU General Public License Usage
  32. ** Alternatively, this file may be used under the terms of the GNU
  33. ** General Public License version 3.0 as published by the Free Software
  34. ** Foundation and appearing in the file LICENSE.GPL included in the
  35. ** packaging of this file. Please review the following information to
  36. ** ensure the GNU General Public License version 3.0 requirements will be
  37. ** met: http://www.gnu.org/copyleft/gpl.html.
  38. **
  39. **
  40. ** $QT_END_LICENSE$
  41. **
  42. ****************************************************************************/
  43. #include "qplatformdefs.h"
  44. #include "qmutex.h"
  45. #include <qdebug.h>
  46. #ifndef QT_NO_THREAD
  47. #include "qatomic.h"
  48. #include "qelapsedtimer.h"
  49. #include "qthread.h"
  50. #include "qmutex_p.h"
  51. #include "qtypetraits.h"
  52. #ifndef QT_LINUX_FUTEX
  53. #include "private/qfreelist_p.h"
  54. #endif
  55. QT_BEGIN_NAMESPACE
  56. static inline bool isRecursive(QMutexData *d)
  57. {
  58. quintptr u = quintptr(d);
  59. if (Q_LIKELY(u <= 0x3))
  60. return false;
  61. #ifdef QT_LINUX_FUTEX
  62. Q_ASSERT(d->recursive);
  63. return true;
  64. #else
  65. return d->recursive;
  66. #endif
  67. }
  68. class QRecursiveMutexPrivate : public QMutexData
  69. {
  70. public:
  71. QRecursiveMutexPrivate()
  72. : QMutexData(QMutex::Recursive), owner(0), count(0) {}
  73. // written to by the thread that first owns 'mutex';
  74. // read during attempts to acquire ownership of 'mutex' from any other thread:
  75. QAtomicPointer<QtPrivate::remove_pointer<Qt::HANDLE>::type> owner;
  76. // only ever accessed from the thread that owns 'mutex':
  77. uint count;
  78. QMutex mutex;
  79. bool lock(int timeout) QT_MUTEX_LOCK_NOEXCEPT;
  80. void unlock() Q_DECL_NOTHROW;
  81. };
  82. /*
  83. \class QBasicMutex
  84. \inmodule QtCore
  85. \brief QMutex POD
  86. \internal
  87. \ingroup thread
  88. - Can be used as global static object.
  89. - Always non-recursive
  90. - Do not use tryLock with timeout > 0, else you can have a leak (see the ~QMutex destructor)
  91. */
  92. /*!
  93. \class QMutex
  94. \inmodule QtCore
  95. \brief The QMutex class provides access serialization between threads.
  96. \threadsafe
  97. \ingroup thread
  98. The purpose of a QMutex is to protect an object, data structure or
  99. section of code so that only one thread can access it at a time
  100. (this is similar to the Java \c synchronized keyword). It is
  101. usually best to use a mutex with a QMutexLocker since this makes
  102. it easy to ensure that locking and unlocking are performed
  103. consistently.
  104. For example, say there is a method that prints a message to the
  105. user on two lines:
  106. \snippet code/src_corelib_thread_qmutex.cpp 0
  107. If these two methods are called in succession, the following happens:
  108. \snippet code/src_corelib_thread_qmutex.cpp 1
  109. If these two methods are called simultaneously from two threads then the
  110. following sequence could result:
  111. \snippet code/src_corelib_thread_qmutex.cpp 2
  112. If we add a mutex, we should get the result we want:
  113. \snippet code/src_corelib_thread_qmutex.cpp 3
  114. Then only one thread can modify \c number at any given time and
  115. the result is correct. This is a trivial example, of course, but
  116. applies to any other case where things need to happen in a
  117. particular sequence.
  118. When you call lock() in a thread, other threads that try to call
  119. lock() in the same place will block until the thread that got the
  120. lock calls unlock(). A non-blocking alternative to lock() is
  121. tryLock().
  122. \sa QMutexLocker, QReadWriteLock, QSemaphore, QWaitCondition
  123. */
  124. /*!
  125. \enum QMutex::RecursionMode
  126. \value Recursive In this mode, a thread can lock the same mutex
  127. multiple times and the mutex won't be unlocked
  128. until a corresponding number of unlock() calls
  129. have been made.
  130. \value NonRecursive In this mode, a thread may only lock a mutex
  131. once.
  132. \sa QMutex()
  133. */
  134. /*!
  135. Constructs a new mutex. The mutex is created in an unlocked state.
  136. If \a mode is QMutex::Recursive, a thread can lock the same mutex
  137. multiple times and the mutex won't be unlocked until a
  138. corresponding number of unlock() calls have been made. Otherwise
  139. a thread may only lock a mutex once. The default is
  140. QMutex::NonRecursive.
  141. \sa lock(), unlock()
  142. */
  143. QMutex::QMutex(RecursionMode mode)
  144. {
  145. d_ptr.store(mode == Recursive ? new QRecursiveMutexPrivate : 0);
  146. }
  147. /*!
  148. Destroys the mutex.
  149. \warning Destroying a locked mutex may result in undefined behavior.
  150. */
  151. QMutex::~QMutex()
  152. {
  153. QMutexData *d = d_ptr.load();
  154. if (isRecursive()) {
  155. delete static_cast<QRecursiveMutexPrivate *>(d);
  156. } else if (d) {
  157. #ifndef QT_LINUX_FUTEX
  158. if (d != dummyLocked() && static_cast<QMutexPrivate *>(d)->possiblyUnlocked.load()
  159. && tryLock()) {
  160. unlock();
  161. return;
  162. }
  163. #endif
  164. qWarning("QMutex: destroying locked mutex");
  165. }
  166. }
  167. /*! \fn void QMutex::lock()
  168. Locks the mutex. If another thread has locked the mutex then this
  169. call will block until that thread has unlocked it.
  170. Calling this function multiple times on the same mutex from the
  171. same thread is allowed if this mutex is a
  172. \l{QMutex::Recursive}{recursive mutex}. If this mutex is a
  173. \l{QMutex::NonRecursive}{non-recursive mutex}, this function will
  174. \e dead-lock when the mutex is locked recursively.
  175. \sa unlock()
  176. */
  177. void QMutex::lock() QT_MUTEX_LOCK_NOEXCEPT
  178. {
  179. QMutexData *current;
  180. if (fastTryLock(current))
  181. return;
  182. if (QT_PREPEND_NAMESPACE(isRecursive)(current))
  183. static_cast<QRecursiveMutexPrivate *>(current)->lock(-1);
  184. else
  185. lockInternal();
  186. }
  187. /*! \fn bool QMutex::tryLock(int timeout)
  188. Attempts to lock the mutex. This function returns \c true if the lock
  189. was obtained; otherwise it returns \c false. If another thread has
  190. locked the mutex, this function will wait for at most \a timeout
  191. milliseconds for the mutex to become available.
  192. Note: Passing a negative number as the \a timeout is equivalent to
  193. calling lock(), i.e. this function will wait forever until mutex
  194. can be locked if \a timeout is negative.
  195. If the lock was obtained, the mutex must be unlocked with unlock()
  196. before another thread can successfully lock it.
  197. Calling this function multiple times on the same mutex from the
  198. same thread is allowed if this mutex is a
  199. \l{QMutex::Recursive}{recursive mutex}. If this mutex is a
  200. \l{QMutex::NonRecursive}{non-recursive mutex}, this function will
  201. \e always return false when attempting to lock the mutex
  202. recursively.
  203. \sa lock(), unlock()
  204. */
  205. bool QMutex::tryLock(int timeout) QT_MUTEX_LOCK_NOEXCEPT
  206. {
  207. QMutexData *current;
  208. if (fastTryLock(current))
  209. return true;
  210. if (QT_PREPEND_NAMESPACE(isRecursive)(current))
  211. return static_cast<QRecursiveMutexPrivate *>(current)->lock(timeout);
  212. else
  213. return lockInternal(timeout);
  214. }
  215. /*! \fn void QMutex::unlock()
  216. Unlocks the mutex. Attempting to unlock a mutex in a different
  217. thread to the one that locked it results in an error. Unlocking a
  218. mutex that is not locked results in undefined behavior.
  219. \sa lock()
  220. */
  221. void QMutex::unlock() Q_DECL_NOTHROW
  222. {
  223. QMutexData *current;
  224. if (fastTryUnlock(current))
  225. return;
  226. if (QT_PREPEND_NAMESPACE(isRecursive)(current))
  227. static_cast<QRecursiveMutexPrivate *>(current)->unlock();
  228. else
  229. unlockInternal();
  230. }
  231. /*!
  232. \fn void QMutex::isRecursive()
  233. \since 5.0
  234. Returns \c true if the mutex is recursive
  235. */
  236. bool QBasicMutex::isRecursive()
  237. {
  238. return QT_PREPEND_NAMESPACE(isRecursive)(d_ptr.loadAcquire());
  239. }
  240. /*!
  241. \class QMutexLocker
  242. \inmodule QtCore
  243. \brief The QMutexLocker class is a convenience class that simplifies
  244. locking and unlocking mutexes.
  245. \threadsafe
  246. \ingroup thread
  247. Locking and unlocking a QMutex in complex functions and
  248. statements or in exception handling code is error-prone and
  249. difficult to debug. QMutexLocker can be used in such situations
  250. to ensure that the state of the mutex is always well-defined.
  251. QMutexLocker should be created within a function where a
  252. QMutex needs to be locked. The mutex is locked when QMutexLocker
  253. is created. You can unlock and relock the mutex with \c unlock()
  254. and \c relock(). If locked, the mutex will be unlocked when the
  255. QMutexLocker is destroyed.
  256. For example, this complex function locks a QMutex upon entering
  257. the function and unlocks the mutex at all the exit points:
  258. \snippet code/src_corelib_thread_qmutex.cpp 4
  259. This example function will get more complicated as it is
  260. developed, which increases the likelihood that errors will occur.
  261. Using QMutexLocker greatly simplifies the code, and makes it more
  262. readable:
  263. \snippet code/src_corelib_thread_qmutex.cpp 5
  264. Now, the mutex will always be unlocked when the QMutexLocker
  265. object is destroyed (when the function returns since \c locker is
  266. an auto variable).
  267. The same principle applies to code that throws and catches
  268. exceptions. An exception that is not caught in the function that
  269. has locked the mutex has no way of unlocking the mutex before the
  270. exception is passed up the stack to the calling function.
  271. QMutexLocker also provides a \c mutex() member function that returns
  272. the mutex on which the QMutexLocker is operating. This is useful
  273. for code that needs access to the mutex, such as
  274. QWaitCondition::wait(). For example:
  275. \snippet code/src_corelib_thread_qmutex.cpp 6
  276. \sa QReadLocker, QWriteLocker, QMutex
  277. */
  278. /*!
  279. \fn QMutexLocker::QMutexLocker(QMutex *mutex)
  280. Constructs a QMutexLocker and locks \a mutex. The mutex will be
  281. unlocked when the QMutexLocker is destroyed. If \a mutex is zero,
  282. QMutexLocker does nothing.
  283. \sa QMutex::lock()
  284. */
  285. /*!
  286. \fn QMutexLocker::~QMutexLocker()
  287. Destroys the QMutexLocker and unlocks the mutex that was locked
  288. in the constructor.
  289. \sa QMutex::unlock()
  290. */
  291. /*!
  292. \fn void QMutexLocker::unlock()
  293. Unlocks this mutex locker. You can use \c relock() to lock
  294. it again. It does not need to be locked when destroyed.
  295. \sa relock()
  296. */
  297. /*!
  298. \fn void QMutexLocker::relock()
  299. Relocks an unlocked mutex locker.
  300. \sa unlock()
  301. */
  302. /*!
  303. \fn QMutex *QMutexLocker::mutex()
  304. Returns the mutex on which the QMutexLocker is operating.
  305. */
  306. #ifndef QT_LINUX_FUTEX //linux implementation is in qmutex_linux.cpp
  307. /*
  308. For a rough introduction on how this works, refer to
  309. http://woboq.com/blog/internals-of-qmutex-in-qt5.html
  310. which explains a slightly simplified version of it.
  311. The differences are that here we try to work with timeout (requires the
  312. possiblyUnlocked flag) and that we only wake one thread when unlocking
  313. (requires maintaining the waiters count)
  314. We also support recursive mutexes which always have a valid d_ptr.
  315. The waiters flag represents the number of threads that are waiting or about
  316. to wait on the mutex. There are two tricks to keep in mind:
  317. We don't want to increment waiters after we checked no threads are waiting
  318. (waiters == 0). That's why we atomically set the BigNumber flag on waiters when
  319. we check waiters. Similarly, if waiters is decremented right after we checked,
  320. the mutex would be unlocked (d->wakeUp() has (or will) be called), but there is
  321. no thread waiting. This is only happening if there was a timeout in tryLock at the
  322. same time as the mutex is unlocked. So when there was a timeout, we set the
  323. possiblyUnlocked flag.
  324. */
  325. /*!
  326. \internal helper for lock()
  327. */
  328. void QBasicMutex::lockInternal() QT_MUTEX_LOCK_NOEXCEPT
  329. {
  330. lockInternal(-1);
  331. }
  332. /*!
  333. \internal helper for lock(int)
  334. */
  335. bool QBasicMutex::lockInternal(int timeout) QT_MUTEX_LOCK_NOEXCEPT
  336. {
  337. Q_ASSERT(!isRecursive());
  338. while (!fastTryLock()) {
  339. QMutexData *copy = d_ptr.loadAcquire();
  340. if (!copy) // if d is 0, the mutex is unlocked
  341. continue;
  342. if (copy == dummyLocked()) {
  343. if (timeout == 0)
  344. return false;
  345. // The mutex is locked but does not have a QMutexPrivate yet.
  346. // we need to allocate a QMutexPrivate
  347. QMutexPrivate *newD = QMutexPrivate::allocate();
  348. if (!d_ptr.testAndSetOrdered(dummyLocked(), newD)) {
  349. //Either the mutex is already unlocked, or another thread already set it.
  350. newD->deref();
  351. continue;
  352. }
  353. copy = newD;
  354. //the d->refCount is already 1 the deref will occurs when we unlock
  355. }
  356. QMutexPrivate *d = static_cast<QMutexPrivate *>(copy);
  357. if (timeout == 0 && !d->possiblyUnlocked.load())
  358. return false;
  359. // At this point we have a pointer to a QMutexPrivate. But the other thread
  360. // may unlock the mutex at any moment and release the QMutexPrivate to the pool.
  361. // We will try to reference it to avoid unlock to release it to the pool to make
  362. // sure it won't be released. But if the refcount is already 0 it has been released.
  363. if (!d->ref())
  364. continue; //that QMutexData was already released
  365. // We now hold a reference to the QMutexPrivate. It won't be released and re-used.
  366. // But it is still possible that it was already re-used by another QMutex right before
  367. // we did the ref(). So check if we still hold a pointer to the right mutex.
  368. if (d != d_ptr.loadAcquire()) {
  369. //Either the mutex is already unlocked, or relocked with another mutex
  370. d->deref();
  371. continue;
  372. }
  373. // In this part, we will try to increment the waiters count.
  374. // We just need to take care of the case in which the old_waiters
  375. // is set to the BigNumber magic value set in unlockInternal()
  376. int old_waiters;
  377. do {
  378. old_waiters = d->waiters.load();
  379. if (old_waiters == -QMutexPrivate::BigNumber) {
  380. // we are unlocking, and the thread that unlocks is about to change d to 0
  381. // we try to acquire the mutex by changing to dummyLocked()
  382. if (d_ptr.testAndSetAcquire(d, dummyLocked())) {
  383. // Mutex acquired
  384. d->deref();
  385. return true;
  386. } else {
  387. Q_ASSERT(d != d_ptr.load()); //else testAndSetAcquire should have succeeded
  388. // Mutex is likely to bo 0, we should continue the outer-loop,
  389. // set old_waiters to the magic value of BigNumber
  390. old_waiters = QMutexPrivate::BigNumber;
  391. break;
  392. }
  393. }
  394. } while (!d->waiters.testAndSetRelaxed(old_waiters, old_waiters + 1));
  395. if (d != d_ptr.loadAcquire()) {
  396. // The mutex was unlocked before we incremented waiters.
  397. if (old_waiters != QMutexPrivate::BigNumber) {
  398. //we did not break the previous loop
  399. Q_ASSERT(d->waiters.load() >= 1);
  400. d->waiters.deref();
  401. }
  402. d->deref();
  403. continue;
  404. }
  405. if (d->wait(timeout)) {
  406. // reset the possiblyUnlocked flag if needed (and deref its corresponding reference)
  407. if (d->possiblyUnlocked.load() && d->possiblyUnlocked.testAndSetRelaxed(true, false))
  408. d->deref();
  409. d->derefWaiters(1);
  410. //we got the lock. (do not deref)
  411. Q_ASSERT(d == d_ptr.load());
  412. return true;
  413. } else {
  414. Q_ASSERT(timeout >= 0);
  415. //timeout
  416. d->derefWaiters(1);
  417. //There may be a race in which the mutex is unlocked right after we timed out,
  418. // and before we deref the waiters, so maybe the mutex is actually unlocked.
  419. // Set the possiblyUnlocked flag to indicate this possibility.
  420. if (!d->possiblyUnlocked.testAndSetRelaxed(false, true)) {
  421. // We keep a reference when possiblyUnlocked is true.
  422. // but if possiblyUnlocked was already true, we don't need to keep the reference.
  423. d->deref();
  424. }
  425. return false;
  426. }
  427. }
  428. Q_ASSERT(d_ptr.load() != 0);
  429. return true;
  430. }
  431. /*!
  432. \internal
  433. */
  434. void QBasicMutex::unlockInternal() Q_DECL_NOTHROW
  435. {
  436. QMutexData *copy = d_ptr.loadAcquire();
  437. Q_ASSERT(copy); //we must be locked
  438. Q_ASSERT(copy != dummyLocked()); // testAndSetRelease(dummyLocked(), 0) failed
  439. Q_ASSERT(!isRecursive());
  440. QMutexPrivate *d = reinterpret_cast<QMutexPrivate *>(copy);
  441. // If no one is waiting for the lock anymore, we should reset d to 0x0.
  442. // Using fetchAndAdd, we atomically check that waiters was equal to 0, and add a flag
  443. // to the waiters variable (BigNumber). That way, we avoid the race in which waiters is
  444. // incremented right after we checked, because we won't increment waiters if is
  445. // equal to -BigNumber
  446. if (d->waiters.fetchAndAddRelease(-QMutexPrivate::BigNumber) == 0) {
  447. //there is no one waiting on this mutex anymore, set the mutex as unlocked (d = 0)
  448. if (d_ptr.testAndSetRelease(d, 0)) {
  449. // reset the possiblyUnlocked flag if needed (and deref its corresponding reference)
  450. if (d->possiblyUnlocked.load() && d->possiblyUnlocked.testAndSetRelaxed(true, false))
  451. d->deref();
  452. }
  453. d->derefWaiters(0);
  454. } else {
  455. d->derefWaiters(0);
  456. //there are thread waiting, transfer the lock.
  457. d->wakeUp();
  458. }
  459. d->deref();
  460. }
  461. //The freelist management
  462. namespace {
  463. struct FreeListConstants : QFreeListDefaultConstants {
  464. enum { BlockCount = 4, MaxIndex=0xffff };
  465. static const int Sizes[BlockCount];
  466. };
  467. const int FreeListConstants::Sizes[FreeListConstants::BlockCount] = {
  468. 16,
  469. 128,
  470. 1024,
  471. FreeListConstants::MaxIndex - (16-128-1024)
  472. };
  473. typedef QFreeList<QMutexPrivate, FreeListConstants> FreeList;
  474. Q_GLOBAL_STATIC(FreeList, freelist);
  475. }
  476. QMutexPrivate *QMutexPrivate::allocate()
  477. {
  478. int i = freelist()->next();
  479. QMutexPrivate *d = &(*freelist())[i];
  480. d->id = i;
  481. Q_ASSERT(d->refCount.load() == 0);
  482. Q_ASSERT(!d->recursive);
  483. Q_ASSERT(!d->possiblyUnlocked.load());
  484. Q_ASSERT(d->waiters.load() == 0);
  485. d->refCount.store(1);
  486. return d;
  487. }
  488. void QMutexPrivate::release()
  489. {
  490. Q_ASSERT(!recursive);
  491. Q_ASSERT(refCount.load() == 0);
  492. Q_ASSERT(!possiblyUnlocked.load());
  493. Q_ASSERT(waiters.load() == 0);
  494. freelist()->release(id);
  495. }
  496. // atomically subtract "value" to the waiters, and remove the QMutexPrivate::BigNumber flag
  497. void QMutexPrivate::derefWaiters(int value) Q_DECL_NOTHROW
  498. {
  499. int old_waiters;
  500. int new_waiters;
  501. do {
  502. old_waiters = waiters.load();
  503. new_waiters = old_waiters;
  504. if (new_waiters < 0) {
  505. new_waiters += QMutexPrivate::BigNumber;
  506. }
  507. new_waiters -= value;
  508. } while (!waiters.testAndSetRelaxed(old_waiters, new_waiters));
  509. }
  510. #endif
  511. /*!
  512. \internal
  513. */
  514. inline bool QRecursiveMutexPrivate::lock(int timeout) QT_MUTEX_LOCK_NOEXCEPT
  515. {
  516. Qt::HANDLE self = QThread::currentThreadId();
  517. if (owner.load() == self) {
  518. ++count;
  519. Q_ASSERT_X(count != 0, "QMutex::lock", "Overflow in recursion counter");
  520. return true;
  521. }
  522. bool success = true;
  523. if (timeout == -1) {
  524. mutex.QBasicMutex::lock();
  525. } else {
  526. success = mutex.tryLock(timeout);
  527. }
  528. if (success)
  529. owner.store(self);
  530. return success;
  531. }
  532. /*!
  533. \internal
  534. */
  535. inline void QRecursiveMutexPrivate::unlock() Q_DECL_NOTHROW
  536. {
  537. if (count > 0) {
  538. count--;
  539. } else {
  540. owner.store(0);
  541. mutex.QBasicMutex::unlock();
  542. }
  543. }
  544. QT_END_NAMESPACE
  545. #ifdef QT_LINUX_FUTEX
  546. # include "qmutex_linux.cpp"
  547. #elif defined(Q_OS_MAC)
  548. # include "qmutex_mac.cpp"
  549. #elif defined(Q_OS_WIN)
  550. # include "qmutex_win.cpp"
  551. #else
  552. # include "qmutex_unix.cpp"
  553. #endif
  554. #endif // QT_NO_THREAD