Scoop API

scoop:scoop.concurrent:0.1.0

src/async_condition.scoop

Selected production source · src/async_condition.scoop

1package scoop.concurrent
3/** A condition associated with one mutex. Always test the protected predicate in a loop. */
4public class AsyncConditionVariable public constructor(public val mutex: AsyncMutex) {
5 private val waiters = WaitQueue<ConditionWaiter>()
7 /** Atomically releases the guard; reacquires that same guard before returning or throwing. */
8 public suspend fun await(guard: AsyncMutexGuard) {
9 ensureActive()
10 suspendCoroutine<Unit> {
11 continuation ->
12 val waiter = ConditionWaiter(guard, continuation)
13 val registration =
14 currentJobOrNone()?.invokeOnCancellation { error -> cancel(waiter, error) }
15 val notifications = WaitNotifications()
16 mutex.stateLock.withLock {
17 waiter.result.bind(registration, notifications)
18 if (waiter.stage == ConditionStage.Registering) {
19 try {
20 mutex.validate(guard)
21 }
22 catch (error: Throwable) {
23 waiter.stage = ConditionStage.Finished
24 waiter.result.fail(error, notifications)
25 return@withLock
26 }
27 waiter.stage = ConditionStage.Waiting
28 waiter.link = Some(waiters.append(waiter))
29 mutex.releaseForCondition(guard, notifications)
30 }
31 Unit
32 }
33 notifications.deliver()
34 }
35 }
37 /** Selects the oldest waiter while holding this condition's mutex. */
38 public fun signal(guard: AsyncMutexGuard) {
39 val notifications = WaitNotifications()
40 mutex.stateLock.withLock {
41 mutex.validate(guard)
42 when (waiters.takeFirst()) {
43 case Some(val waiter) -> select(waiter, None, notifications)
44 case None -> {}
45 }
46 }
47 notifications.deliver()
48 }
50 /** Selects all current waiters in registration order. Notifications are not saved. */
51 public fun broadcast(guard: AsyncMutexGuard) {
52 val notifications = WaitNotifications()
53 mutex.stateLock.withLock {
54 mutex.validate(guard)
55 while (!waiters.isEmpty)
56 select(waiters.takeFirst()!!, None, notifications)
57 }
58 notifications.deliver()
59 }
61 private fun select(
62 waiter: ConditionWaiter,
63 failure: Throwable?,
64 notifications: WaitNotifications
65 ) {
66 waiter.link = None
67 waiter.stage = ConditionStage.Acquiring
68 waiter.failure = failure
69 waiter.result.detachCancellation(notifications)
70 mutex.reacquire(waiter, notifications)
71 }
73 private fun cancel(waiter: ConditionWaiter, error: CancellationException) {
74 val notifications = WaitNotifications()
75 mutex.stateLock.withLock {
76 when (waiter.stage) {
77 case Registering -> {
78 waiter.stage = ConditionStage.Finished
79 waiter.result.fail(error, notifications)
80 }
81 case Waiting -> {
82 waiters.remove(waiter.link!!)
83 select(waiter, Some(error), notifications)
84 }
85 case Acquiring -> {}
86 case Finished -> {}
87 }
88 }
89 notifications.deliver()
90 }