Simpler write() action
Useful Int.times(block) extension
This commit is contained in:
@@ -0,0 +1,9 @@
|
|||||||
|
package std
|
||||||
|
|
||||||
|
inline fun Int.times(body : () -> Unit) {
|
||||||
|
var count = this;
|
||||||
|
while (count > 0) {
|
||||||
|
body()
|
||||||
|
count--
|
||||||
|
}
|
||||||
|
}
|
||||||
+4
-28
@@ -42,15 +42,9 @@ Returns result of the calculation
|
|||||||
*/
|
*/
|
||||||
inline fun <erased T> ReentrantReadWriteLock.write(action: ()->T) : T {
|
inline fun <erased T> ReentrantReadWriteLock.write(action: ()->T) : T {
|
||||||
val rl = readLock().sure()
|
val rl = readLock().sure()
|
||||||
var upgradeCount = getWriteHoldCount()
|
|
||||||
if(upgradeCount == 0) {
|
val readCount = if (getWriteHoldCount() == 0) getReadHoldCount() else 0
|
||||||
upgradeCount = getReadHoldCount()
|
readCount times { rl.unlock() }
|
||||||
if(upgradeCount > 0)
|
|
||||||
rl.unlock(upgradeCount)
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
upgradeCount = 0
|
|
||||||
}
|
|
||||||
|
|
||||||
val wl = writeLock().sure()
|
val wl = writeLock().sure()
|
||||||
wl.lock()
|
wl.lock()
|
||||||
@@ -58,25 +52,7 @@ inline fun <erased T> ReentrantReadWriteLock.write(action: ()->T) : T {
|
|||||||
return action()
|
return action()
|
||||||
}
|
}
|
||||||
finally {
|
finally {
|
||||||
if(upgradeCount > 0) {
|
readCount times { rl.lock() }
|
||||||
rl.lock(upgradeCount)
|
|
||||||
}
|
|
||||||
wl.unlock()
|
wl.unlock()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
inline private fun ReadLock.lock(readCount: Int) {
|
|
||||||
if(readCount > 0) {
|
|
||||||
for(j in 1..readCount) {
|
|
||||||
lock()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
inline private fun ReadLock.unlock(readCount: Int) {
|
|
||||||
if(readCount > 0) {
|
|
||||||
for(j in 1..readCount) {
|
|
||||||
unlock()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
Reference in New Issue
Block a user