Scoop API

scoop:scoop.asyncio:0.1.0

src/loop/loop_drive.scoop

Selected production source · src/loop/loop_drive.scoop

1package scoop.asyncio
3// Only the owner thread enters the driver. Nested host notifications schedule another turn.
4internal class LoopDriver {
5 private var pumping: Boolean = false
6 private var pumpAgain: Boolean = false
7 // The owner lends empty storage to each producer and keeps its snapshot for this turn.
8 private var commands = ArrayList<LoopWork>()
9 private var localCommands = ArrayList<LoopWork>()
10 private var ready = ArrayList<LoopWork>()
12 fun pump(owner: LoopOwner, native: Ptr<Unit>): Boolean {
13 if (pumping) {
14 pumpAgain = true;
15 return false
16 }
17 pumping = true
18 try {
19 commands = owner.takeCommands(commands)
20 localCommands = owner.takeLocalCommands(localCommands)
21 owner.poll(native, false)
22 @Unsafe
23 {
24 val completions = nativeLoopTakeBatch(native)
25 runBatch(commands)
26 runBatch(localCommands)
27 var index = 0L
28 while (index < completions.count) {
29 owner.complete(decodeEvent(completions.records.load(index)))
30 index += 1L
31 }
32 }
33 owner.startCleanup()
34 ready = owner.takeReady(ready)
35 runBatch(ready)
36 owner.startCleanup()
37 owner.advanceTimers()
38 owner.dispatchBlocking(native)
39 } finally {
40 owner.flushTransfers()
41 commands.clear()
42 localCommands.clear()
43 ready.clear()
44 pumping = false
45 @Unsafe
46 {
47 nativeLoopRearm(native, pumpAgain || owner.hasQueuedWork())
48 }
49 pumpAgain = false
50 }
51 return true
52 }
54 private fun runBatch(batch: ArrayList<LoopWork>) {
55 var index = 0L
56 while (index < batch.size) {
57 batch[index].run()
58 index += 1L
59 }
60 }
62 fun drive(owner: LoopOwner, native: Ptr<Unit>) {
63 while (true) {
64 pump(owner, native)
65 if (owner.stopIfDrained(native))
66 break
67 if (!owner.hasQueuedWork())
68 owner.poll(native, true)
69 }
70 when (owner.destroy(native)) {
71 case Some(val error) -> throw error
72 case None -> {}
73 }
74 }