| 108 | } |
| 109 | |
| 110 | bool DUChainLock::lockForWrite(uint timeout) |
| 111 | { |
| 112 | Q_D(DUChainLock); |
| 113 | |
| 114 | //It is not allowed to acquire a write-lock while holding read-lock |
| 115 | |
| 116 | Q_ASSERT(d->ownReaderRecursion() == 0); |
| 117 | |
| 118 | if (d->m_writer.loadRelaxed() == QThread::currentThread()) { |
| 119 | //We already hold the write lock, just increase the recursion count and return |
| 120 | d->m_writerRecursion.fetchAndAddRelaxed(1); |
| 121 | return true; |
| 122 | } |
| 123 | |
| 124 | QElapsedTimer t; |
| 125 | if (timeout) { |
| 126 | t.start(); |
| 127 | } |
| 128 | |
| 129 | while (1) { |
| 130 | //Try acquiring the write-lcok |
| 131 | if (d->m_totalReaderRecursion.loadRelaxed() == 0 && d->m_writerRecursion.testAndSetOrdered(0, 1)) { |
| 132 | //Now we can be sure that there is no other writer, as we have increased m_writerRecursion from 0 to 1 |
| 133 | d->m_writer = QThread::currentThread(); |
| 134 | if (d->m_totalReaderRecursion.loadRelaxed() == 0) { |
| 135 | //There is still no readers, we have successfully acquired a write-lock |
| 136 | return true; |
| 137 | } else { |
| 138 | //There may be readers.. we have to continue spinning |
| 139 | d->m_writer = nullptr; |
| 140 | d->m_writerRecursion = 0; |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | if (!timeout || t.elapsed() < timeout) { |
| 145 | QThread::usleep(uSleepTime); |
| 146 | } else { |
| 147 | //Fail! |
| 148 | return false; |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | return false; |
| 153 | } |
| 154 | |
| 155 | void DUChainLock::releaseWriteLock() |
| 156 | { |
no test coverage detected