This commit is contained in:
2026-10-18 19:45:28 +06:00
parent c400ed4c3e
commit ae8af4868e
3 changed files with 31 additions and 1 deletions

View File

@@ -50,7 +50,7 @@ sealed interface SmartMutex {
override val lockStateFlow: StateFlow<Boolean> = _lockStateFlow.asStateFlow()
private val internalChangesMutex = Mutex()
private val backingMutex = Mutex()
private val backingMutex = Mutex(locked = locked)
fun immutable() = Immutable(lockStateFlow)

View File

@@ -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()

View File

@@ -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()