Scoop API

scoop:scoop.concurrent:0.1.0

src/async_mutex.scoop

Selected production source · src/async_mutex.scoop

1package scoop.concurrent
3import scoop.platform.concurrent.Mutex
5/** A non-reentrant FIFO mutex whose ownership may move between managed threads. */
6public class AsyncMutex public constructor() {
7 internal val stateLock = Mutex()
8 private var holder: AsyncMutexGuard? = None
9 private val waiters = WaitQueue<MutexWaiter>()
11 /** Acquires a guard, suspending without blocking the executor while contended. */
12 public suspend fun lock(): AsyncMutexGuard {
13 ensureActive()
14 return suspendCoroutine<AsyncMutexGuard> {
15 continuation ->
16 val waiter = MutexAcquisition(AsyncMutexGuard(this), continuation)
17 val registration =
18 currentJobOrNone()?.invokeOnCancellation { error -> cancel(waiter, error) }
19 val notifications = WaitNotifications()
20 stateLock.withLock {
21 waiter.result.bind(registration, notifications)
22 if (waiter.result.isPending) {
23 if (!waitPresent(holder))
24 grant(waiter, notifications)
25 else
26 waiter.link = Some(waiters.append(waiter))
27 }
28 Unit
29 }
30 notifications.deliver()
31 }
32 }
34 /** Acquires only if immediately available, without overtaking queued waiters. */
35 public fun tryLock(): AsyncMutexGuard? =
36 stateLock.withLock {
37 if (waitPresent(holder))
38 return@withLock None
39 val guard = AsyncMutexGuard(this)
40 guard.state = GuardState.Held
41 holder = Some(guard)
42 Some(guard)
43 }
45 /** Releases the acquired guard when the ordinary block returns or throws. */
46 public suspend fun <T> withLock(block: AsyncMutexGuard.() -> T): T {
47 val guard = lock()
48 try {
49 return block(guard)
50 }
51 finally {
52 guard.dispose()
53 }
54 }
56 /** Keeps ownership across suspension, and releases on return, failure or cancellation. */
57 public suspend fun <T> withLock(block: suspend AsyncMutexGuard.() -> T): T {
58 val guard = lock()
59 try {
60 return block(guard)
61 }
62 finally {
63 guard.dispose()
64 }
65 }
67 internal fun validate(guard: AsyncMutexGuard) {
68 val owns =
69 when (holder) {
70 case Some(val current) -> current === guard
71 case None -> false
72 }
73 if (guard.mutex !== this || guard.state != GuardState.Held || !owns)
74 throw IllegalStateException(Some("guard does not hold this mutex"))
75 }
77 internal fun release(guard: AsyncMutexGuard) {
78 val notifications = WaitNotifications()
79 stateLock.withLock {
80 if (guard.state != GuardState.Released) {
81 validate(guard)
82 guard.state = GuardState.Released
83 handoff(notifications)
84 }
85 Unit
86 }
87 notifications.deliver()
88 }
90 internal fun releaseForCondition(guard: AsyncMutexGuard, notifications: WaitNotifications) {
91 guard.state = GuardState.ConditionWaiting
92 handoff(notifications)
93 }
95 internal fun reacquire(waiter: MutexWaiter, notifications: WaitNotifications) {
96 if (!waitPresent(holder))
97 grant(waiter, notifications)
98 else
99 waiters.append(waiter)
100 }
102 private fun handoff(notifications: WaitNotifications) {
103 when (waiters.takeFirst()) {
104 case Some(val waiter) -> grant(waiter, notifications)
105 case None -> holder = None
106 }
107 }
109 private fun grant(waiter: MutexWaiter, notifications: WaitNotifications) {
110 holder = Some(waiter.guard)
111 waiter.guard.state = GuardState.Held
112 waiter.acquired(notifications)
113 }
115 private fun cancel(waiter: MutexAcquisition, error: CancellationException) {
116 val notifications = WaitNotifications()
117 stateLock.withLock {
118 if (waiter.result.isPending) {
119 when (waiter.link) {
120 case Some(val link) -> waiters.remove(link)
121 case None -> {}
122 }
123 waiter.link = None
124 waiter.result.fail(error, notifications)
125 }
126 Unit
127 }
128 notifications.deliver()
129 }
132/** Shared ownership state for a single acquisition; disposal is idempotent after release. */
133public class AsyncMutexGuard internal constructor(internal val mutex: AsyncMutex): Disposable {
134 internal var state: GuardState = GuardState.Released
136 /** Releases once; condition-waiting guards cannot be released until reacquired. */
137 public override fun dispose() {
138 mutex.release(this)
139 }
142internal enum GuardState {
143 Held, ConditionWaiting, Released