Scoop API

scoop:scoop.asyncio:0.1.0

src/loop/loop_inbox.scoop

Selected production source · src/loop/loop_inbox.scoop

1package scoop.asyncio
3import scoop.platform.concurrent.Mutex
5// The notification stays alive until all publishers have left this boundary.
6internal class LoopInbox {
7 private val lock = Mutex()
8 private var native: Ptr<Unit>? = None
9 private var commands = ArrayList<LoopWork>()
11 fun open(pointer: Ptr<Unit>) {
12 lock.withLock { native = Some(pointer) }
13 }
15 fun post(command: LoopWork, required: Boolean = false) {
16 lock.withLock {
17 when (native) {
18 case Some(val pointer) -> {
19 val notify = commands.size == 0L
20 commands.add(command)
21 if (notify) {
22 @Unsafe
23 {
24 nativeLoopWake(pointer)
25 }
26 }
27 Unit
28 }
29 case None -> {
30 if (required)
31 throw IllegalStateException(Some("event loop executor is closed"))
32 Unit
33 }
34 }
35 }
36 }
38 fun wake() {
39 lock.withLock {
40 when (native) {
41 case Some(val pointer) -> @Unsafe
42 {
43 nativeLoopWake(pointer)
44 }
45 case None -> {}
46 }
47 }
48 }
50 fun take(empty: ArrayList<LoopWork>): ArrayList<LoopWork> {
51 return lock.withLock {
52 val batch = commands
53 commands = empty
54 batch
55 }
56 }
58 fun hasCommands(): Boolean = lock.withLock { commands.size != 0L }
60 fun closeIfEmpty(): Boolean =
61 lock.withLock {
62 if (commands.size != 0L)
63 false
64 else {
65 native = None
66 true
67 }
68 }