diff --git a/coroutines/src/commonMain/kotlin/dev/inmo/micro_utils/coroutines/SmartMutex.kt b/coroutines/src/commonMain/kotlin/dev/inmo/micro_utils/coroutines/SmartMutex.kt index 2c7b2de738e..39484174c76 100644 --- a/coroutines/src/commonMain/kotlin/dev/inmo/micro_utils/coroutines/SmartMutex.kt +++ b/coroutines/src/commonMain/kotlin/dev/inmo/micro_utils/coroutines/SmartMutex.kt @@ -50,7 +50,7 @@ sealed interface SmartMutex { override val lockStateFlow: StateFlow = _lockStateFlow.asStateFlow() private val internalChangesMutex = Mutex() - private val backingMutex = Mutex() + private val backingMutex = Mutex(locked = locked) fun immutable() = Immutable(lockStateFlow) diff --git a/coroutines/src/commonTest/kotlin/SmartMutexTests.kt b/coroutines/src/commonTest/kotlin/SmartMutexTests.kt index 90019408539..2cf5acefd2e 100644 --- a/coroutines/src/commonTest/kotlin/SmartMutexTests.kt +++ b/coroutines/src/commonTest/kotlin/SmartMutexTests.kt @@ -14,6 +14,17 @@ import kotlin.test.assertTrue import kotlin.time.Duration.Companion.seconds class SmartMutexTests { + @Test + fun initiallyLockedMutexCanBeReleasedAndReacquired() = runTest(timeout = 5.seconds) { + val mutex = SmartMutex.Mutable(locked = true) + assertTrue(mutex.isLocked) + assertFalse(mutex.tryLock()) + assertTrue(mutex.unlock()) + assertFalse(mutex.isLocked) + assertTrue(mutex.tryLock()) + assertTrue(mutex.unlock()) + } + @Test fun cancelledUnlockCompletesUnderContention() = runTest(timeout = 5.seconds) { val mutex = SmartMutex.Mutable() diff --git a/coroutines/src/commonTest/kotlin/SmartRWLockerTests.kt b/coroutines/src/commonTest/kotlin/SmartRWLockerTests.kt index de4b374a9a3..4defaa84bad 100644 --- a/coroutines/src/commonTest/kotlin/SmartRWLockerTests.kt +++ b/coroutines/src/commonTest/kotlin/SmartRWLockerTests.kt @@ -13,6 +13,25 @@ import kotlin.time.Duration.Companion.days import kotlin.time.Duration.Companion.seconds class SmartRWLockerTests { + @Test + fun initiallyWriteLockedLockerReleasesReadPermits() = runTest(timeout = 5.seconds) { + val locker = SmartRWLocker(readPermits = 2, writeIsLocked = true) + assertTrue(locker.writeMutex.isLocked) + assertEquals(0, locker.readSemaphore.freePermits) + + assertTrue(locker.unlockWrite()) + + assertFalse(locker.writeMutex.isLocked) + assertEquals(2, locker.readSemaphore.freePermits) + locker.withReadAcquire { + assertEquals(1, locker.readSemaphore.freePermits) + } + locker.withWriteLock { + assertEquals(0, locker.readSemaphore.freePermits) + } + assertEquals(2, locker.readSemaphore.freePermits) + } + @Test fun compositeTest() { val locker = SmartRWLocker()