Scoop API

scoop:scoop.asyncio:0.1.0

src/loop/single_loop.scoop

Selected production source · src/loop/single_loop.scoop

1package scoop.asyncio
3import scoop.asyncio.host.EventLoopHost
5internal class SingleLoop(private val config: LoopBlockingConfig) {
6 private val accepted = AtomicBoolean(false)
7 val state = LoopOwner()
9 /**
10 * Runs the root structured scope and drives its operations to completion. The loop is
11 * single-use and cannot be nested or called from an existing Job.
12 */
13 fun <T> run(loop: EventLoop, block: suspend CoroutineScope.() -> T): T {
14 requireLoopRootCaller()
15 return runPrepared(loop, block)
16 }
18 private fun <T> runPrepared(loop: EventLoop, block: suspend CoroutineScope.() -> T): T {
19 acceptInstance()
20 val native = state.open(loop, config)
21 val result = LoopResult<T>()
22 context(loop) {
23 startDispatchedCoroutine<T>(
24 state.executor,
25 {
26 coroutineScope<T> {
27 this @SingleLoop.state.bindRoot(job)
28 block(this)
29 }
30 },
31 LoopCompletion(state, result)
32 )
33 }
34 state.drive(native)
35 @Unsafe
36 {
37 return result.value.assumeInit()
38 }
39 }
41 /** Attaches without running application callbacks on the registration stack. */
42 fun attach(
43 loop: EventLoop,
44 host: EventLoopHost,
45 onClosed: (Throwable?) -> Unit
46 ): EventLoopSession {
47 if (!host.isCurrentThread())
48 throw IllegalStateException(Some("attach requires the host owner thread"))
49 acceptStart()
50 val native = state.open(loop, config)
51 val mailbox = LoopMailbox(state)
52 context(loop) {
53 startDispatchedCoroutine<Unit>(
54 state.executor,
55 {
56 coroutineScope<Unit> {
57 val scope = this
58 mailbox.run(scope)
59 }
60 },
61 SessionCompletion(mailbox)
62 )
63 }
64 try {
65 LoopAttachment(state, native, mailbox, onClosed).install(host)
66 } catch (error: Throwable) {
67 mailbox.requestClose()
68 try {
69 state.drive(native)
70 } catch (cleanup: Throwable) {
71 throw ResourceUseException(error, cleanup)
72 }
73 throw error
74 }
75 return EventLoopSession(loop, mailbox)
76 }
78 private fun acceptStart() {
79 requireLoopRootCaller()
80 acceptInstance()
81 }
83 private fun acceptInstance() {
84 if (!accepted.compareAndSet(false, true))
85 throw IllegalStateException(Some("event loop already used"))
86 }
89private class LoopResult<T> {
90 var value: MaybeUninit<T> = MaybeUninit<T>.uninit()
93private class LoopCompletion<T>(
94 val state: LoopOwner,
95 private val result: LoopResult<T>
96) : Continuation<T> {
97 public override fun resume(value: T) {
98 result.value = MaybeUninit<T>.initialized(value)
99 state.finishRoot(None)
100 }
101 public override fun resumeWithException(exception: Throwable) {
102 state.finishRoot(Some(exception))
103 }