Last active
March 2, 2021 04:29
-
-
Save emizzle/485d8f6ba2d1cb14feaea1933cbd6797 to your computer and use it in GitHub Desktop.
Nim task runner simple ping pong use case
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import chronicles, chronos, task_runner | |
type | |
ThreadArg = object | |
chanRecv: AsyncChannel[ThreadSafeString] | |
chanSend: AsyncChannel[ThreadSafeString] | |
# forward declarations | |
proc worker(arg: ThreadArg) {.async.} | |
proc workerThread(arg: ThreadArg) {.thread.} | |
proc runPingPong() {.async.} = | |
let chanRecv = newAsyncChannel[ThreadSafeString](-1) | |
let chanSend = newAsyncChannel[ThreadSafeString](-1) | |
let arg = ThreadArg(chanRecv: chanSend, chanSend: chanRecv) | |
var thr = Thread[ThreadArg]() | |
chanRecv.open() | |
chanSend.open() | |
createThread(thr, workerThread, arg) | |
while true: | |
info "[ping-pong test] waiting for message" | |
# park while waiting for a message | |
let received = $(await chanRecv.recv()) | |
info "[ping-pong test] received message", message=received | |
case received | |
of "ready": | |
let message = "hello" | |
info "[ping-pong test] sending message", message=message | |
await chanSend.send(message.safe) | |
of "world": | |
let message = "shutdown" | |
info "[ping-pong test] sending message", message=message | |
await chanSend.send(message.safe) | |
info "[ping-pong test] breaking while loop" | |
break | |
# we will only get here AFTER we receive "shutdown" | |
# and we break out of the while loop | |
joinThread(thr) | |
chanRecv.close() | |
chanSend.close() | |
proc worker(arg: ThreadArg) {.async.} = | |
let chanRecv = arg.chanRecv | |
let chanSend = arg.chanSend | |
chanRecv.open() | |
chanSend.open() | |
info "[ping-pong worker] sending message", message="ready" | |
await chanSend.send("ready".safe) | |
while true: | |
info "[ping-pong worker] waiting for message" | |
let received = $(await chanRecv.recv()) | |
info "[ping-pong worker] received message", message=received | |
case received | |
of "hello": | |
let message = "world" | |
info "[ping-pong worker] sending message", message=message | |
await chanSend.send(message.safe) | |
of "shutdown": | |
info "[ping-pong worker] breaking while loop" | |
break | |
chanRecv.close() | |
chanSend.close() | |
proc workerThread(arg: ThreadArg) {.thread.} = | |
waitFor worker(arg) | |
when isMainModule: | |
waitFor runPingPong() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment