| 1 | /**************************************************************************** |
| 2 | ** |
| 3 | ** Copyright (C) 2016 The Qt Company Ltd. |
| 4 | ** Copyright (C) 2016 Intel Corporation. |
| 5 | ** Copyright (C) 2012 Olivier Goffart <ogoffart@woboq.com> |
| 6 | ** Contact: https://www.qt.io/licensing/ |
| 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 The Qt Company. For licensing terms |
| 16 | ** and conditions see https://www.qt.io/terms-conditions. For further |
| 17 | ** information use the contact form at https://www.qt.io/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 3 as published by the Free Software |
| 22 | ** Foundation and appearing in the file LICENSE.LGPL3 included in the |
| 23 | ** packaging of this file. Please review the following information to |
| 24 | ** ensure the GNU Lesser General Public License version 3 requirements |
| 25 | ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. |
| 26 | ** |
| 27 | ** GNU General Public License Usage |
| 28 | ** Alternatively, this file may be used under the terms of the GNU |
| 29 | ** General Public License version 2.0 or (at your option) the GNU General |
| 30 | ** Public license version 3 or any later version approved by the KDE Free |
| 31 | ** Qt Foundation. The licenses are as published by the Free Software |
| 32 | ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 |
| 33 | ** included in the packaging of this file. Please review the following |
| 34 | ** information to ensure the GNU General Public License requirements will |
| 35 | ** be met: https://www.gnu.org/licenses/gpl-2.0.html and |
| 36 | ** https://www.gnu.org/licenses/gpl-3.0.html. |
| 37 | ** |
| 38 | ** $QT_END_LICENSE$ |
| 39 | ** |
| 40 | ****************************************************************************/ |
| 41 | |
| 42 | #include "qplatformdefs.h" |
| 43 | #include "qmutex.h" |
| 44 | #include <qdebug.h> |
| 45 | #include "qatomic.h" |
| 46 | #include "qelapsedtimer.h" |
| 47 | #include "qthread.h" |
| 48 | #include "qmutex_p.h" |
| 49 | |
| 50 | #ifndef QT_LINUX_FUTEX |
| 51 | #include "private/qfreelist_p.h" |
| 52 | #endif |
| 53 | |
| 54 | QT_BEGIN_NAMESPACE |
| 55 | |
| 56 | /* |
| 57 | \class QBasicMutex |
| 58 | \inmodule QtCore |
| 59 | \brief QMutex POD |
| 60 | \internal |
| 61 | |
| 62 | \ingroup thread |
| 63 | |
| 64 | - Can be used as global static object. |
| 65 | - Always non-recursive |
| 66 | - Do not use tryLock with timeout > 0, else you can have a leak (see the ~QMutex destructor) |
| 67 | */ |
| 68 | |
| 69 | /*! |
| 70 | \class QMutex |
| 71 | \inmodule QtCore |
| 72 | \brief The QMutex class provides access serialization between threads. |
| 73 | |
| 74 | \threadsafe |
| 75 | |
| 76 | \ingroup thread |
| 77 | |
| 78 | The purpose of a QMutex is to protect an object, data structure or |
| 79 | section of code so that only one thread can access it at a time |
| 80 | (this is similar to the Java \c synchronized keyword). It is |
| 81 | usually best to use a mutex with a QMutexLocker since this makes |
| 82 | it easy to ensure that locking and unlocking are performed |
| 83 | consistently. |
| 84 | |
| 85 | For example, say there is a method that prints a message to the |
| 86 | user on two lines: |
| 87 | |
| 88 | \snippet code/src_corelib_thread_qmutex.cpp 0 |
| 89 | |
| 90 | If these two methods are called in succession, the following happens: |
| 91 | |
| 92 | \snippet code/src_corelib_thread_qmutex.cpp 1 |
| 93 | |
| 94 | If these two methods are called simultaneously from two threads then the |
| 95 | following sequence could result: |
| 96 | |
| 97 | \snippet code/src_corelib_thread_qmutex.cpp 2 |
| 98 | |
| 99 | If we add a mutex, we should get the result we want: |
| 100 | |
| 101 | \snippet code/src_corelib_thread_qmutex.cpp 3 |
| 102 | |
| 103 | Then only one thread can modify \c number at any given time and |
| 104 | the result is correct. This is a trivial example, of course, but |
| 105 | applies to any other case where things need to happen in a |
| 106 | particular sequence. |
| 107 | |
| 108 | When you call lock() in a thread, other threads that try to call |
| 109 | lock() in the same place will block until the thread that got the |
| 110 | lock calls unlock(). A non-blocking alternative to lock() is |
| 111 | tryLock(). |
| 112 | |
| 113 | QMutex is optimized to be fast in the non-contended case. It |
| 114 | will not allocate memory if there is no contention on that mutex. |
| 115 | It is constructed and destroyed with almost no overhead, |
| 116 | which means it is fine to have many mutexes as part of other classes. |
| 117 | |
| 118 | \sa QRecursiveMutex, QMutexLocker, QReadWriteLock, QSemaphore, QWaitCondition |
| 119 | */ |
| 120 | |
| 121 | /*! |
| 122 | \fn QMutex::QMutex() |
| 123 | |
| 124 | Constructs a new mutex. The mutex is created in an unlocked state. |
| 125 | */ |
| 126 | |
| 127 | /*! \fn QMutex::~QMutex() |
| 128 | |
| 129 | Destroys the mutex. |
| 130 | |
| 131 | \warning Destroying a locked mutex may result in undefined behavior. |
| 132 | */ |
| 133 | void QBasicMutex::destroyInternal(QMutexPrivate *d) |
| 134 | { |
| 135 | if (!d) |
| 136 | return; |
| 137 | #ifndef QT_LINUX_FUTEX |
| 138 | if (d != dummyLocked() && d->possiblyUnlocked.loadRelaxed() && tryLock()) { |
| 139 | unlock(); |
| 140 | return; |
| 141 | } |
| 142 | #endif |
| 143 | qWarning("QMutex: destroying locked mutex" ); |
| 144 | } |
| 145 | |
| 146 | /*! \fn void QMutex::lock() |
| 147 | |
| 148 | Locks the mutex. If another thread has locked the mutex then this |
| 149 | call will block until that thread has unlocked it. |
| 150 | |
| 151 | Calling this function multiple times on the same mutex from the |
| 152 | same thread will cause a \e dead-lock. |
| 153 | |
| 154 | \sa unlock() |
| 155 | */ |
| 156 | |
| 157 | /*! \fn bool QMutex::tryLock(int timeout) |
| 158 | |
| 159 | Attempts to lock the mutex. This function returns \c true if the lock |
| 160 | was obtained; otherwise it returns \c false. If another thread has |
| 161 | locked the mutex, this function will wait for at most \a timeout |
| 162 | milliseconds for the mutex to become available. |
| 163 | |
| 164 | Note: Passing a negative number as the \a timeout is equivalent to |
| 165 | calling lock(), i.e. this function will wait forever until mutex |
| 166 | can be locked if \a timeout is negative. |
| 167 | |
| 168 | If the lock was obtained, the mutex must be unlocked with unlock() |
| 169 | before another thread can successfully lock it. |
| 170 | |
| 171 | Calling this function multiple times on the same mutex from the |
| 172 | same thread will cause a \e dead-lock. |
| 173 | |
| 174 | \sa lock(), unlock() |
| 175 | */ |
| 176 | |
| 177 | /*! \fn bool QMutex::tryLock() |
| 178 | \overload |
| 179 | |
| 180 | Attempts to lock the mutex. This function returns \c true if the lock |
| 181 | was obtained; otherwise it returns \c false. |
| 182 | |
| 183 | If the lock was obtained, the mutex must be unlocked with unlock() |
| 184 | before another thread can successfully lock it. |
| 185 | |
| 186 | Calling this function multiple times on the same mutex from the |
| 187 | same thread will cause a \e dead-lock. |
| 188 | |
| 189 | \sa lock(), unlock() |
| 190 | */ |
| 191 | |
| 192 | /*! \fn bool QMutex::try_lock() |
| 193 | \since 5.8 |
| 194 | |
| 195 | Attempts to lock the mutex. This function returns \c true if the lock |
| 196 | was obtained; otherwise it returns \c false. |
| 197 | |
| 198 | This function is provided for compatibility with the Standard Library |
| 199 | concept \c Lockable. It is equivalent to tryLock(). |
| 200 | */ |
| 201 | |
| 202 | /*! \fn template <class Rep, class Period> bool QMutex::try_lock_for(std::chrono::duration<Rep, Period> duration) |
| 203 | \since 5.8 |
| 204 | |
| 205 | Attempts to lock the mutex. This function returns \c true if the lock |
| 206 | was obtained; otherwise it returns \c false. If another thread has |
| 207 | locked the mutex, this function will wait for at least \a duration |
| 208 | for the mutex to become available. |
| 209 | |
| 210 | Note: Passing a negative duration as the \a duration is equivalent to |
| 211 | calling try_lock(). This behavior differs from tryLock(). |
| 212 | |
| 213 | If the lock was obtained, the mutex must be unlocked with unlock() |
| 214 | before another thread can successfully lock it. |
| 215 | |
| 216 | Calling this function multiple times on the same mutex from the |
| 217 | same thread will cause a \e dead-lock. |
| 218 | |
| 219 | \sa lock(), unlock() |
| 220 | */ |
| 221 | |
| 222 | /*! \fn template<class Clock, class Duration> bool QMutex::try_lock_until(std::chrono::time_point<Clock, Duration> timePoint) |
| 223 | \since 5.8 |
| 224 | |
| 225 | Attempts to lock the mutex. This function returns \c true if the lock |
| 226 | was obtained; otherwise it returns \c false. If another thread has |
| 227 | locked the mutex, this function will wait at least until \a timePoint |
| 228 | for the mutex to become available. |
| 229 | |
| 230 | Note: Passing a \a timePoint which has already passed is equivalent |
| 231 | to calling try_lock(). This behavior differs from tryLock(). |
| 232 | |
| 233 | If the lock was obtained, the mutex must be unlocked with unlock() |
| 234 | before another thread can successfully lock it. |
| 235 | |
| 236 | Calling this function multiple times on the same mutex from the |
| 237 | same thread will cause a \e dead-lock. |
| 238 | |
| 239 | \sa lock(), unlock() |
| 240 | */ |
| 241 | |
| 242 | /*! \fn void QMutex::unlock() |
| 243 | |
| 244 | Unlocks the mutex. Attempting to unlock a mutex in a different |
| 245 | thread to the one that locked it results in an error. Unlocking a |
| 246 | mutex that is not locked results in undefined behavior. |
| 247 | |
| 248 | \sa lock() |
| 249 | */ |
| 250 | |
| 251 | /*! |
| 252 | \class QRecursiveMutex |
| 253 | \inmodule QtCore |
| 254 | \since 5.14 |
| 255 | \brief The QRecursiveMutex class provides access serialization between threads. |
| 256 | |
| 257 | \threadsafe |
| 258 | |
| 259 | \ingroup thread |
| 260 | |
| 261 | The QRecursiveMutex class is a mutex, like QMutex, with which it is |
| 262 | API-compatible. It differs from QMutex by accepting lock() calls from |
| 263 | the same thread any number of times. QMutex would deadlock in this situation. |
| 264 | |
| 265 | QRecursiveMutex is much more expensive to construct and operate on, so |
| 266 | use a plain QMutex whenever you can. Sometimes, one public function, |
| 267 | however, calls another public function, and they both need to lock the |
| 268 | same mutex. In this case, you have two options: |
| 269 | |
| 270 | \list |
| 271 | \li Factor the code that needs mutex protection into private functions, |
| 272 | which assume that the mutex is held when they are called, and lock a |
| 273 | plain QMutex in the public functions before you call the private |
| 274 | implementation ones. |
| 275 | \li Or use a recursive mutex, so it doesn't matter that the first public |
| 276 | function has already locked the mutex when the second one wishes to do so. |
| 277 | \endlist |
| 278 | |
| 279 | \sa QMutex, QMutexLocker, QReadWriteLock, QSemaphore, QWaitCondition |
| 280 | */ |
| 281 | |
| 282 | /*! \fn QRecursiveMutex::QRecursiveMutex() |
| 283 | |
| 284 | Constructs a new recursive mutex. The mutex is created in an unlocked state. |
| 285 | |
| 286 | \sa lock(), unlock() |
| 287 | */ |
| 288 | |
| 289 | /*! |
| 290 | Destroys the mutex. |
| 291 | |
| 292 | \warning Destroying a locked mutex may result in undefined behavior. |
| 293 | */ |
| 294 | QRecursiveMutex::~QRecursiveMutex() |
| 295 | { |
| 296 | } |
| 297 | |
| 298 | /*! \fn void QRecursiveMutex::lock() |
| 299 | |
| 300 | Locks the mutex. If another thread has locked the mutex then this |
| 301 | call will block until that thread has unlocked it. |
| 302 | |
| 303 | Calling this function multiple times on the same mutex from the |
| 304 | same thread is allowed. |
| 305 | |
| 306 | \sa unlock() |
| 307 | */ |
| 308 | |
| 309 | /*! |
| 310 | Attempts to lock the mutex. This function returns \c true if the lock |
| 311 | was obtained; otherwise it returns \c false. If another thread has |
| 312 | locked the mutex, this function will wait for at most \a timeout |
| 313 | milliseconds for the mutex to become available. |
| 314 | |
| 315 | Note: Passing a negative number as the \a timeout is equivalent to |
| 316 | calling lock(), i.e. this function will wait forever until mutex |
| 317 | can be locked if \a timeout is negative. |
| 318 | |
| 319 | If the lock was obtained, the mutex must be unlocked with unlock() |
| 320 | before another thread can successfully lock it. |
| 321 | |
| 322 | Calling this function multiple times on the same mutex from the |
| 323 | same thread is allowed. |
| 324 | |
| 325 | \sa lock(), unlock() |
| 326 | */ |
| 327 | bool QRecursiveMutex::tryLock(int timeout) QT_MUTEX_LOCK_NOEXCEPT |
| 328 | { |
| 329 | Qt::HANDLE self = QThread::currentThreadId(); |
| 330 | if (owner.loadRelaxed() == self) { |
| 331 | ++count; |
| 332 | Q_ASSERT_X(count != 0, "QMutex::lock" , "Overflow in recursion counter" ); |
| 333 | return true; |
| 334 | } |
| 335 | bool success = true; |
| 336 | if (timeout == -1) { |
| 337 | mutex.lock(); |
| 338 | } else { |
| 339 | success = mutex.tryLock(timeout); |
| 340 | } |
| 341 | |
| 342 | if (success) |
| 343 | owner.storeRelaxed(self); |
| 344 | return success; |
| 345 | } |
| 346 | |
| 347 | /*! \fn bool QRecursiveMutex::try_lock() |
| 348 | \since 5.8 |
| 349 | |
| 350 | Attempts to lock the mutex. This function returns \c true if the lock |
| 351 | was obtained; otherwise it returns \c false. |
| 352 | |
| 353 | This function is provided for compatibility with the Standard Library |
| 354 | concept \c Lockable. It is equivalent to tryLock(). |
| 355 | */ |
| 356 | |
| 357 | /*! \fn template <class Rep, class Period> bool QRecursiveMutex::try_lock_for(std::chrono::duration<Rep, Period> duration) |
| 358 | \since 5.8 |
| 359 | |
| 360 | Attempts to lock the mutex. This function returns \c true if the lock |
| 361 | was obtained; otherwise it returns \c false. If another thread has |
| 362 | locked the mutex, this function will wait for at least \a duration |
| 363 | for the mutex to become available. |
| 364 | |
| 365 | Note: Passing a negative duration as the \a duration is equivalent to |
| 366 | calling try_lock(). This behavior differs from tryLock(). |
| 367 | |
| 368 | If the lock was obtained, the mutex must be unlocked with unlock() |
| 369 | before another thread can successfully lock it. |
| 370 | |
| 371 | Calling this function multiple times on the same mutex from the |
| 372 | same thread is allowed. |
| 373 | |
| 374 | \sa lock(), unlock() |
| 375 | */ |
| 376 | |
| 377 | /*! \fn template<class Clock, class Duration> bool QRecursiveMutex::try_lock_until(std::chrono::time_point<Clock, Duration> timePoint) |
| 378 | \since 5.8 |
| 379 | |
| 380 | Attempts to lock the mutex. This function returns \c true if the lock |
| 381 | was obtained; otherwise it returns \c false. If another thread has |
| 382 | locked the mutex, this function will wait at least until \a timePoint |
| 383 | for the mutex to become available. |
| 384 | |
| 385 | Note: Passing a \a timePoint which has already passed is equivalent |
| 386 | to calling try_lock(). This behavior differs from tryLock(). |
| 387 | |
| 388 | If the lock was obtained, the mutex must be unlocked with unlock() |
| 389 | before another thread can successfully lock it. |
| 390 | |
| 391 | Calling this function multiple times on the same mutex from the |
| 392 | same thread is allowed. |
| 393 | |
| 394 | \sa lock(), unlock() |
| 395 | */ |
| 396 | |
| 397 | /*! |
| 398 | Unlocks the mutex. Attempting to unlock a mutex in a different |
| 399 | thread to the one that locked it results in an error. Unlocking a |
| 400 | mutex that is not locked results in undefined behavior. |
| 401 | |
| 402 | \sa lock() |
| 403 | */ |
| 404 | void QRecursiveMutex::unlock() noexcept |
| 405 | { |
| 406 | Q_ASSERT(owner.loadRelaxed() == QThread::currentThreadId()); |
| 407 | |
| 408 | if (count > 0) { |
| 409 | count--; |
| 410 | } else { |
| 411 | owner.storeRelaxed(nullptr); |
| 412 | mutex.unlock(); |
| 413 | } |
| 414 | } |
| 415 | |
| 416 | |
| 417 | /*! |
| 418 | \class QMutexLocker |
| 419 | \inmodule QtCore |
| 420 | \brief The QMutexLocker class is a convenience class that simplifies |
| 421 | locking and unlocking mutexes. |
| 422 | |
| 423 | \threadsafe |
| 424 | |
| 425 | \ingroup thread |
| 426 | |
| 427 | Locking and unlocking a QMutex or QRecursiveMutex in complex functions and |
| 428 | statements or in exception handling code is error-prone and |
| 429 | difficult to debug. QMutexLocker can be used in such situations |
| 430 | to ensure that the state of the mutex is always well-defined. |
| 431 | |
| 432 | QMutexLocker should be created within a function where a |
| 433 | QMutex needs to be locked. The mutex is locked when QMutexLocker |
| 434 | is created. You can unlock and relock the mutex with \c unlock() |
| 435 | and \c relock(). If locked, the mutex will be unlocked when the |
| 436 | QMutexLocker is destroyed. |
| 437 | |
| 438 | For example, this complex function locks a QMutex upon entering |
| 439 | the function and unlocks the mutex at all the exit points: |
| 440 | |
| 441 | \snippet code/src_corelib_thread_qmutex.cpp 4 |
| 442 | |
| 443 | This example function will get more complicated as it is |
| 444 | developed, which increases the likelihood that errors will occur. |
| 445 | |
| 446 | Using QMutexLocker greatly simplifies the code, and makes it more |
| 447 | readable: |
| 448 | |
| 449 | \snippet code/src_corelib_thread_qmutex.cpp 5 |
| 450 | |
| 451 | Now, the mutex will always be unlocked when the QMutexLocker |
| 452 | object is destroyed (when the function returns since \c locker is |
| 453 | an auto variable). |
| 454 | |
| 455 | The same principle applies to code that throws and catches |
| 456 | exceptions. An exception that is not caught in the function that |
| 457 | has locked the mutex has no way of unlocking the mutex before the |
| 458 | exception is passed up the stack to the calling function. |
| 459 | |
| 460 | QMutexLocker also provides a \c mutex() member function that returns |
| 461 | the mutex on which the QMutexLocker is operating. This is useful |
| 462 | for code that needs access to the mutex, such as |
| 463 | QWaitCondition::wait(). For example: |
| 464 | |
| 465 | \snippet code/src_corelib_thread_qmutex.cpp 6 |
| 466 | |
| 467 | \sa QReadLocker, QWriteLocker, QMutex |
| 468 | */ |
| 469 | |
| 470 | /*! |
| 471 | \fn template <typename Mutex> QMutexLocker<Mutex>::QMutexLocker(Mutex *mutex) noexcept |
| 472 | |
| 473 | Constructs a QMutexLocker and locks \a mutex. The mutex will be |
| 474 | unlocked when the QMutexLocker is destroyed. If \a mutex is \nullptr, |
| 475 | QMutexLocker does nothing. |
| 476 | |
| 477 | \sa QMutex::lock() |
| 478 | */ |
| 479 | |
| 480 | /*! |
| 481 | \fn template <typename Mutex> QMutexLocker<Mutex>::~QMutexLocker() noexcept |
| 482 | |
| 483 | Destroys the QMutexLocker and unlocks the mutex that was locked |
| 484 | in the constructor. |
| 485 | |
| 486 | \sa QMutex::unlock() |
| 487 | */ |
| 488 | |
| 489 | /*! |
| 490 | \fn template <typename Mutex> void QMutexLocker<Mutex>::unlock() noexcept |
| 491 | |
| 492 | Unlocks this mutex locker. You can use \c relock() to lock |
| 493 | it again. It does not need to be locked when destroyed. |
| 494 | |
| 495 | \sa relock() |
| 496 | */ |
| 497 | |
| 498 | /*! |
| 499 | \fn template <typename Mutex> void QMutexLocker<Mutex>::relock() noexcept |
| 500 | |
| 501 | Relocks an unlocked mutex locker. |
| 502 | |
| 503 | \sa unlock() |
| 504 | */ |
| 505 | |
| 506 | /*! |
| 507 | \fn template <typename Mutex> QMutex *QMutexLocker<Mutex>::mutex() const |
| 508 | |
| 509 | Returns the mutex on which the QMutexLocker is operating. |
| 510 | |
| 511 | */ |
| 512 | |
| 513 | #ifndef QT_LINUX_FUTEX //linux implementation is in qmutex_linux.cpp |
| 514 | |
| 515 | /* |
| 516 | For a rough introduction on how this works, refer to |
| 517 | http://woboq.com/blog/internals-of-qmutex-in-qt5.html |
| 518 | which explains a slightly simplified version of it. |
| 519 | The differences are that here we try to work with timeout (requires the |
| 520 | possiblyUnlocked flag) and that we only wake one thread when unlocking |
| 521 | (requires maintaining the waiters count) |
| 522 | We also support recursive mutexes which always have a valid d_ptr. |
| 523 | |
| 524 | The waiters flag represents the number of threads that are waiting or about |
| 525 | to wait on the mutex. There are two tricks to keep in mind: |
| 526 | We don't want to increment waiters after we checked no threads are waiting |
| 527 | (waiters == 0). That's why we atomically set the BigNumber flag on waiters when |
| 528 | we check waiters. Similarly, if waiters is decremented right after we checked, |
| 529 | the mutex would be unlocked (d->wakeUp() has (or will) be called), but there is |
| 530 | no thread waiting. This is only happening if there was a timeout in tryLock at the |
| 531 | same time as the mutex is unlocked. So when there was a timeout, we set the |
| 532 | possiblyUnlocked flag. |
| 533 | */ |
| 534 | |
| 535 | /*! |
| 536 | \internal helper for lock() |
| 537 | */ |
| 538 | void QBasicMutex::lockInternal() QT_MUTEX_LOCK_NOEXCEPT |
| 539 | { |
| 540 | lockInternal(-1); |
| 541 | } |
| 542 | |
| 543 | /*! |
| 544 | \internal helper for lock(int) |
| 545 | */ |
| 546 | bool QBasicMutex::lockInternal(int timeout) QT_MUTEX_LOCK_NOEXCEPT |
| 547 | { |
| 548 | while (!fastTryLock()) { |
| 549 | QMutexPrivate *copy = d_ptr.loadAcquire(); |
| 550 | if (!copy) // if d is 0, the mutex is unlocked |
| 551 | continue; |
| 552 | |
| 553 | if (copy == dummyLocked()) { |
| 554 | if (timeout == 0) |
| 555 | return false; |
| 556 | // The mutex is locked but does not have a QMutexPrivate yet. |
| 557 | // we need to allocate a QMutexPrivate |
| 558 | QMutexPrivate *newD = QMutexPrivate::allocate(); |
| 559 | if (!d_ptr.testAndSetOrdered(dummyLocked(), newD)) { |
| 560 | //Either the mutex is already unlocked, or another thread already set it. |
| 561 | newD->deref(); |
| 562 | continue; |
| 563 | } |
| 564 | copy = newD; |
| 565 | //the d->refCount is already 1 the deref will occurs when we unlock |
| 566 | } |
| 567 | |
| 568 | QMutexPrivate *d = static_cast<QMutexPrivate *>(copy); |
| 569 | if (timeout == 0 && !d->possiblyUnlocked.loadRelaxed()) |
| 570 | return false; |
| 571 | |
| 572 | // At this point we have a pointer to a QMutexPrivate. But the other thread |
| 573 | // may unlock the mutex at any moment and release the QMutexPrivate to the pool. |
| 574 | // We will try to reference it to avoid unlock to release it to the pool to make |
| 575 | // sure it won't be released. But if the refcount is already 0 it has been released. |
| 576 | if (!d->ref()) |
| 577 | continue; //that QMutexPrivate was already released |
| 578 | |
| 579 | // We now hold a reference to the QMutexPrivate. It won't be released and re-used. |
| 580 | // But it is still possible that it was already re-used by another QMutex right before |
| 581 | // we did the ref(). So check if we still hold a pointer to the right mutex. |
| 582 | if (d != d_ptr.loadAcquire()) { |
| 583 | //Either the mutex is already unlocked, or relocked with another mutex |
| 584 | d->deref(); |
| 585 | continue; |
| 586 | } |
| 587 | |
| 588 | // In this part, we will try to increment the waiters count. |
| 589 | // We just need to take care of the case in which the old_waiters |
| 590 | // is set to the BigNumber magic value set in unlockInternal() |
| 591 | int old_waiters; |
| 592 | do { |
| 593 | old_waiters = d->waiters.loadRelaxed(); |
| 594 | if (old_waiters == -QMutexPrivate::BigNumber) { |
| 595 | // we are unlocking, and the thread that unlocks is about to change d to 0 |
| 596 | // we try to acquire the mutex by changing to dummyLocked() |
| 597 | if (d_ptr.testAndSetAcquire(d, dummyLocked())) { |
| 598 | // Mutex acquired |
| 599 | d->deref(); |
| 600 | return true; |
| 601 | } else { |
| 602 | Q_ASSERT(d != d_ptr.loadRelaxed()); //else testAndSetAcquire should have succeeded |
| 603 | // Mutex is likely to bo 0, we should continue the outer-loop, |
| 604 | // set old_waiters to the magic value of BigNumber |
| 605 | old_waiters = QMutexPrivate::BigNumber; |
| 606 | break; |
| 607 | } |
| 608 | } |
| 609 | } while (!d->waiters.testAndSetRelaxed(old_waiters, old_waiters + 1)); |
| 610 | |
| 611 | if (d != d_ptr.loadAcquire()) { |
| 612 | // The mutex was unlocked before we incremented waiters. |
| 613 | if (old_waiters != QMutexPrivate::BigNumber) { |
| 614 | //we did not break the previous loop |
| 615 | Q_ASSERT(d->waiters.loadRelaxed() >= 1); |
| 616 | d->waiters.deref(); |
| 617 | } |
| 618 | d->deref(); |
| 619 | continue; |
| 620 | } |
| 621 | |
| 622 | if (d->wait(timeout)) { |
| 623 | // reset the possiblyUnlocked flag if needed (and deref its corresponding reference) |
| 624 | if (d->possiblyUnlocked.loadRelaxed() && d->possiblyUnlocked.testAndSetRelaxed(true, false)) |
| 625 | d->deref(); |
| 626 | d->derefWaiters(1); |
| 627 | //we got the lock. (do not deref) |
| 628 | Q_ASSERT(d == d_ptr.loadRelaxed()); |
| 629 | return true; |
| 630 | } else { |
| 631 | Q_ASSERT(timeout >= 0); |
| 632 | //timeout |
| 633 | d->derefWaiters(1); |
| 634 | //There may be a race in which the mutex is unlocked right after we timed out, |
| 635 | // and before we deref the waiters, so maybe the mutex is actually unlocked. |
| 636 | // Set the possiblyUnlocked flag to indicate this possibility. |
| 637 | if (!d->possiblyUnlocked.testAndSetRelaxed(false, true)) { |
| 638 | // We keep a reference when possiblyUnlocked is true. |
| 639 | // but if possiblyUnlocked was already true, we don't need to keep the reference. |
| 640 | d->deref(); |
| 641 | } |
| 642 | return false; |
| 643 | } |
| 644 | } |
| 645 | Q_ASSERT(d_ptr.loadRelaxed() != 0); |
| 646 | return true; |
| 647 | } |
| 648 | |
| 649 | /*! |
| 650 | \internal |
| 651 | */ |
| 652 | void QBasicMutex::unlockInternal() noexcept |
| 653 | { |
| 654 | QMutexPrivate *copy = d_ptr.loadAcquire(); |
| 655 | Q_ASSERT(copy); //we must be locked |
| 656 | Q_ASSERT(copy != dummyLocked()); // testAndSetRelease(dummyLocked(), 0) failed |
| 657 | |
| 658 | QMutexPrivate *d = reinterpret_cast<QMutexPrivate *>(copy); |
| 659 | |
| 660 | // If no one is waiting for the lock anymore, we should reset d to 0x0. |
| 661 | // Using fetchAndAdd, we atomically check that waiters was equal to 0, and add a flag |
| 662 | // to the waiters variable (BigNumber). That way, we avoid the race in which waiters is |
| 663 | // incremented right after we checked, because we won't increment waiters if is |
| 664 | // equal to -BigNumber |
| 665 | if (d->waiters.fetchAndAddRelease(-QMutexPrivate::BigNumber) == 0) { |
| 666 | //there is no one waiting on this mutex anymore, set the mutex as unlocked (d = 0) |
| 667 | if (d_ptr.testAndSetRelease(d, 0)) { |
| 668 | // reset the possiblyUnlocked flag if needed (and deref its corresponding reference) |
| 669 | if (d->possiblyUnlocked.loadRelaxed() && d->possiblyUnlocked.testAndSetRelaxed(true, false)) |
| 670 | d->deref(); |
| 671 | } |
| 672 | d->derefWaiters(0); |
| 673 | } else { |
| 674 | d->derefWaiters(0); |
| 675 | //there are thread waiting, transfer the lock. |
| 676 | d->wakeUp(); |
| 677 | } |
| 678 | d->deref(); |
| 679 | } |
| 680 | |
| 681 | //The freelist management |
| 682 | namespace { |
| 683 | struct FreeListConstants : QFreeListDefaultConstants { |
| 684 | enum { BlockCount = 4, MaxIndex=0xffff }; |
| 685 | static const int Sizes[BlockCount]; |
| 686 | }; |
| 687 | const int FreeListConstants::Sizes[FreeListConstants::BlockCount] = { |
| 688 | 16, |
| 689 | 128, |
| 690 | 1024, |
| 691 | FreeListConstants::MaxIndex - (16 + 128 + 1024) |
| 692 | }; |
| 693 | |
| 694 | typedef QFreeList<QMutexPrivate, FreeListConstants> FreeList; |
| 695 | // We cannot use Q_GLOBAL_STATIC because it uses QMutex |
| 696 | static FreeList freeList_; |
| 697 | FreeList *freelist() |
| 698 | { |
| 699 | return &freeList_; |
| 700 | } |
| 701 | } |
| 702 | |
| 703 | QMutexPrivate *QMutexPrivate::allocate() |
| 704 | { |
| 705 | int i = freelist()->next(); |
| 706 | QMutexPrivate *d = &(*freelist())[i]; |
| 707 | d->id = i; |
| 708 | Q_ASSERT(d->refCount.loadRelaxed() == 0); |
| 709 | Q_ASSERT(!d->possiblyUnlocked.loadRelaxed()); |
| 710 | Q_ASSERT(d->waiters.loadRelaxed() == 0); |
| 711 | d->refCount.storeRelaxed(1); |
| 712 | return d; |
| 713 | } |
| 714 | |
| 715 | void QMutexPrivate::release() |
| 716 | { |
| 717 | Q_ASSERT(refCount.loadRelaxed() == 0); |
| 718 | Q_ASSERT(!possiblyUnlocked.loadRelaxed()); |
| 719 | Q_ASSERT(waiters.loadRelaxed() == 0); |
| 720 | freelist()->release(id); |
| 721 | } |
| 722 | |
| 723 | // atomically subtract "value" to the waiters, and remove the QMutexPrivate::BigNumber flag |
| 724 | void QMutexPrivate::derefWaiters(int value) noexcept |
| 725 | { |
| 726 | int old_waiters; |
| 727 | int new_waiters; |
| 728 | do { |
| 729 | old_waiters = waiters.loadRelaxed(); |
| 730 | new_waiters = old_waiters; |
| 731 | if (new_waiters < 0) { |
| 732 | new_waiters += QMutexPrivate::BigNumber; |
| 733 | } |
| 734 | new_waiters -= value; |
| 735 | } while (!waiters.testAndSetRelaxed(old_waiters, new_waiters)); |
| 736 | } |
| 737 | #endif |
| 738 | |
| 739 | QT_END_NAMESPACE |
| 740 | |
| 741 | #ifdef QT_LINUX_FUTEX |
| 742 | # include "qmutex_linux.cpp" |
| 743 | #elif defined(Q_OS_MAC) |
| 744 | # include "qmutex_mac.cpp" |
| 745 | #elif defined(Q_OS_WIN) |
| 746 | # include "qmutex_win.cpp" |
| 747 | #else |
| 748 | # include "qmutex_unix.cpp" |
| 749 | #endif |
| 750 | |