Scoop API

scoop:scoop.asyncio:0.1.0

src/runtime_reactor.scoop

Selected production source · src/runtime_reactor.scoop

1package scoop.asyncio
3import scoop.concurrent.BlockingTaskPool
4import scoop.concurrent.CoroutineWorkerDriver
6internal class RuntimeReactor(
7 private val runtime: RuntimeEventLoop,
8 private val index: Int
9): CoroutineWorkerDriver {
10 val owner = LoopOwner(Some(runtime), index)
11 private var native: Ptr<Unit>? = None
12 private var recordedFailure: Throwable? = None
13 val failure: Throwable? get() = recordedFailure
15 fun open(pool: BlockingTaskPool) {
16 native = Some(owner.open(runtime, LoopBlockingConfig.Shared(pool)))
17 }
19 public override fun enter() {
20 RuntimeWorkerContext.enter(runtime.identity, index)
21 }
23 public override fun poll() {
24 owner.pump(native!!)
25 }
27 public override fun park() {
28 if (!owner.hasQueuedWork())
29 owner.poll(native!!, true)
30 }
32 public override fun wake() {
33 owner.wakeExecution()
34 }
36 public override fun close() {
37 when (native) {
38 case Some(val pointer) -> {
39 try {
40 owner.finishRoot(None)
41 owner.drive(pointer)
42 } catch (error: Throwable) {
43 recordedFailure = Some(error)
44 } finally {
45 native = None
46 RuntimeWorkerContext.leave(runtime.identity)
47 }
48 }
49 case None -> {}
50 }
51 }
54@ThreadLocal
55private var physicalRuntime: Long = 0L
57@ThreadLocal
58private var physicalReactor: Int = -1
60// Only scalar identities live in TLS; moving managed references remain in the runtime graph.
61internal object RuntimeWorkerContext {
62 private val identities = AtomicLong(1L)
64 fun nextIdentity(): Long = identities.fetchAdd(1L)
66 fun enter(runtime: Long, reactor: Int) {
67 @Unsafe
68 {
69 physicalRuntime = runtime
70 physicalReactor = reactor
71 }
72 }
74 fun leave(runtime: Long) {
75 @Unsafe
76 {
77 if (physicalRuntime == runtime) {
78 physicalRuntime = 0L
79 physicalReactor = -1
80 }
81 }
82 }
84 fun current(runtime: Long): Int {
85 @Unsafe
86 {
87 return if (physicalRuntime == runtime)
88 physicalReactor
89 else
90 -1
91 }
92 }