Simpler write() action

Useful Int.times(block) extension
This commit is contained in:
Maxim Shafirov
2012-02-01 16:27:57 +04:00
parent 68a264154f
commit 699c43fe58
2 changed files with 13 additions and 28 deletions
+9
View File
@@ -0,0 +1,9 @@
package std
inline fun Int.times(body : () -> Unit) {
var count = this;
while (count > 0) {
body()
count--
}
}
+4 -28
View File
@@ -42,15 +42,9 @@ Returns result of the calculation
*/
inline fun <erased T> ReentrantReadWriteLock.write(action: ()->T) : T {
val rl = readLock().sure()
var upgradeCount = getWriteHoldCount()
if(upgradeCount == 0) {
upgradeCount = getReadHoldCount()
if(upgradeCount > 0)
rl.unlock(upgradeCount)
}
else {
upgradeCount = 0
}
val readCount = if (getWriteHoldCount() == 0) getReadHoldCount() else 0
readCount times { rl.unlock() }
val wl = writeLock().sure()
wl.lock()
@@ -58,25 +52,7 @@ inline fun <erased T> ReentrantReadWriteLock.write(action: ()->T) : T {
return action()
}
finally {
if(upgradeCount > 0) {
rl.lock(upgradeCount)
}
readCount times { rl.lock() }
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()
}
}
}