Skip to content

Commit bf4efa5

Browse files
authored
Merge pull request #36 from fvasco/master
Add Mutex.withMutex
2 parents a8c1cd4 + e73899d commit bf4efa5

File tree

1 file changed

+15
-1
lines changed
  • kotlinx-coroutines-core/src/main/kotlin/kotlinx/coroutines/experimental/sync

1 file changed

+15
-1
lines changed

kotlinx-coroutines-core/src/main/kotlin/kotlinx/coroutines/experimental/sync/Mutex.kt

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,20 @@ public interface Mutex {
9191
public fun unlock(owner: Any? = null)
9292
}
9393

94+
/**
95+
* Executes the given [action] under this mutex.
96+
* @return the return value of the action.
97+
*/
98+
// :todo: this function needs to be make inline as soon as this bug is fixed: https://youtrack.jetbrains.com/issue/KT-16448
99+
public suspend fun <T> Mutex.withMutex(action: suspend () -> T): T {
100+
lock()
101+
try {
102+
return action()
103+
} finally {
104+
unlock()
105+
}
106+
}
107+
94108
internal class MutexImpl(locked: Boolean) : Mutex {
95109
// State is: Empty | LockedQueue | OpDescriptor
96110
@Volatile
@@ -396,4 +410,4 @@ internal class MutexImpl(locked: Boolean) : Mutex {
396410
return if (affected._state === queue) UNLOCK_FAIL else null
397411
}
398412
}
399-
}
413+
}

0 commit comments

Comments
 (0)