I'm learning async programming and struggling how to run multiple heavy processes.
I understand how I can implement it with threadpool,
import threadpool, times, os, strformat
proc sleepEcho(time: int) =
sleep(time)
echo "slept for ", time, "ms"
let starttime = epochTime()
spawn sleepEcho(2) # I want this,
spawn sleepEcho(3) # and this to start at once
sync()
echo fmt"Time taken: {(epochTime() - starttime)*1000:.2f}(ms)"
which echos
slept for 2ms
slept for 3ms
Time taken: 3.00(ms)
I've been strugling for a while how to implement this with async.
The following code is what I've tried,
import times, asyncdispatch, os, strformat
proc sleepEcho(time: int) {.async.} =
sleep(time)
echo "slept for ", time, "ms"
let starttime = epochTime()
discard sleepEcho(2) # I want this,
discard sleepEcho(3) # and this to start at once
echo fmt"Time taken: {(epochTime() - starttime)*1000:.2f}(ms)"
whose result was
slept for 2ms
slept for 3ms
Time taken: 5.21(ms)
which showed that the second sleepEcho starts AFTER the first sleepEcho terminated.
Thank you for your reply. It went perfectly well.
import times, asyncdispatch, os, strformat
proc sleepEcho(time: int) {.async.} =
await sleepAsync(time)
echo "slept for ", time, "ms"
let a = sleepEcho(2)
let b = sleepEcho(3)
let starttime = epochTime()
while true:
poll()
if a.finished and b.finished:
break
echo fmt"Time taken: {(epochTime() - starttime)*1000:.2f}(ms)"