-
Notifications
You must be signed in to change notification settings - Fork 17
/
work.nim
49 lines (37 loc) · 1.1 KB
/
work.nim
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import cps, deques
###########################################################################
# Implementation of a minimal scheduler, just a dequeue of work
###########################################################################
type
Work = ref object of Continuation
pool: Pool
Pool = ref object
workQueue: Deque[Work]
proc push(pool: Pool, w: Work) =
if w.running:
w.pool = pool
pool.workQueue.addLast(w)
template push(pool: Pool; c: typed) =
pool.push(Work whelp c)
proc jield(c: Work): Work {.cpsMagic.} =
c.pool.push c
proc run(pool: Pool) =
while pool.workQueue.len > 0:
var w = pool.workQueue.popFirst
pool.push w.trampoline
###########################################################################
# Main code
###########################################################################
proc job(id: string, n: int) {.cps:Work.} =
echo "job ", id, " in"
var i = 0
while i < n:
echo "job ", id, ": ", i
jield()
inc i
echo "job ", id, " out"
let pool = Pool()
pool.push job("cat", 3)
pool.push job("dog", 5)
pool.push job("pig", 3)
pool.run()