Nim has async/await type coroutines for concurrency within a single thread
Channels are designed for communication between threads, but if you compile with --threads:on it's certainly possible to use them in coroutines.
Here's a simple demonstration of two coroutines passing messages to a third, all concurrent with the main thread.
import asyncdispatch,strformat,random
var chan: Channel[string] #global declaration
template fakeDelay() = await sleepAsync(rand(2))
proc f(name:string) {.async.} =
for i in 0..6:
echo &"{name}: {i}"
if i==3: chan.send(&"{name}:halfway done")
fakeDelay
proc monitor() {.async.} =
while true:
let tmp = chan.tryRecv
if tmp.dataAvailable:
echo tmp.msg
else: await sleepAsync(1)
proc main() = #main doesn't need to be async
chan.open()
let steve = f("steve")
let mary = f("mary")
asyncCheck monitor() #we don't wait for monitor to finish, so we don't need its Future
echo "main thread continues"
waitFor(steve and mary)
main()
output:
steve: 0
mary: 0
main thread continues
mary: 1
steve: 1
mary: 2
steve: 2
mary: 3
mary:halfway done
steve: 3
mary: 4
steve:halfway done
mary: 5
steve: 4
mary: 6
steve: 5
steve: 6