Scoop API

scoop:scoop.asyncio:0.1.0

src/async_runtime.scoop

Selected production source · src/async_runtime.scoop

1package scoop.asyncio
3import scoop.concurrent.BlockingTaskPool
4import scoop.concurrent.multiThreadExecutor
6/** Runs coroutines and I/O on the same managed workers, sharing one logical event loop. */
7public class AsyncRuntime internal constructor(private val config: AsyncRuntimeConfig) {
8 private val accepted = AtomicBoolean(false)
10 /** Returns the root result after tasks, I/O resources and both worker groups have closed. */
11 public fun <T> run(block: suspend CoroutineScope.() -> T): T {
12 requireLoopRootCaller()
13 if (!accepted.compareAndSet(false, true))
14 throw IllegalStateException(Some("async runtime already used"))
15 val result = RuntimeResult<T>()
16 val configuration = config
17 BlockingTaskPool(configuration.blockingThreads).use {
18 pool -> RuntimeEventLoop.create(configuration.workers, pool).use {
19 runtime -> multiThreadExecutor {
20 workers = configuration.workers
21 blocking(pool)
22 drivers(runtime.drivers)
23 }.use {
24 executor ->
25 runtime.bindExecutor(executor)
26 val loop: EventLoop = runtime
27 context(loop) {
28 startDispatchedCoroutine<T>(
29 executor,
30 {
31 coroutineScope<T> {
32 runtime.bindRoot(job)
33 block(this)
34 }
35 },
36 result
37 )
38 }
39 result.await()
40 runtime.rootFailure = result.failure
41 }
42 }
43 }
44 @Unsafe
45 {
46 return result.value.assumeInit()
47 }
48 }