Skip to content

Commit e6c69e3

Browse files
committed
satisfy grinds
1 parent 71aa24d commit e6c69e3

File tree

1 file changed

+14
-11
lines changed

1 file changed

+14
-11
lines changed

examples/coroutine.nim

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,44 +4,47 @@ import cps, std/sugar
44
type
55
Coroutine = ref object of Continuation
66
data: int
7-
next: Coroutine
7+
suspended: Coroutine
88

99
# Used to both launch and continue the execution of coroutines
10-
template resume(c: Coroutine): Coroutine =
11-
trampoline c
10+
template resume(c: Coroutine): untyped =
11+
discard trampoline c
1212

1313
proc recv(c: Coroutine): int {.cpsVoodoo.} =
1414
c.data
1515

1616
# Suspend execution of the coroutine
17-
proc jield(c: Coroutine): Coroutine {.cpsMagic.} =
18-
c.next = c
19-
return nil
17+
proc suspend(c: Coroutine): Coroutine {.cpsMagic.} =
18+
c.suspended = c
2019

2120
proc send(c: Coroutine, n: int) =
2221
c.data = n
23-
discard c.next.resume()
22+
resume c.suspended
2423

2524
# This coroutine receives the data, applies f and sends the result to consumer
2625
proc filter(dest: Coroutine, f: proc(x: int): int) {.cps:Coroutine.} =
2726
while true:
28-
jield()
27+
suspend()
2928
let n = f(recv())
3029
dest.send(n)
3130

3231
# This coroutine receives ints through filter and prints them
3332
proc consumer() {.cps:Coroutine.} =
3433
while true:
35-
jield()
34+
suspend()
3635
let value = recv()
3736
echo value
3837

3938
let coro2 = whelp consumer()
4039
let coro1 = whelp filter(coro2, x => x * 2)
4140

42-
discard coro1.resume()
43-
discard coro2.resume()
41+
resume coro1
42+
resume coro2
4443

4544
# This prints numbers from 2 to 20 in 2 increment.
4645
for i in 1..10:
4746
coro1.send(i)
47+
48+
# break the cycles
49+
reset coro1.suspended
50+
reset coro2.suspended

0 commit comments

Comments
 (0)