Skip to content

Instantly share code, notes, and snippets.

@z-------------
Last active January 24, 2023 07:56
Show Gist options
  • Save z-------------/2a46fd0b0df04de642b9bc86a89a6467 to your computer and use it in GitHub Desktop.
Save z-------------/2a46fd0b0df04de642b9bc86a89a6467 to your computer and use it in GitHub Desktop.
import std/asyncdispatch
proc asyncThread*[T](worker: proc (arg: T) {.thread.}; arg: T): Future[void] {.async.} =
## Starts a thread that runs `worker` and completes the Future when the thread exits.
var fut = newFuture[void]("asyncThread")
let ev = newAsyncEvent()
addEvent(ev) do (_: AsyncFD) -> bool:
fut.complete()
true
proc wrapper(args: tuple[worker: proc (arg: T) {.thread.}; arg: T; ev: AsyncEvent]) {.thread.} =
args.worker(args.arg)
args.ev.trigger()
var thr: Thread[(proc (arg: T) {.thread.}, T, AsyncEvent)]
createThread(thr, wrapper, (worker, arg, ev))
await fut
joinThread(thr)
when isMainModule:
import std/os
proc worker(arg: string) {.thread.} =
echo "\tthread arg: ", arg
sleep(milsecs = 1000)
echo "\tthread done."
echo "program start"
waitFor asyncThread(worker, "hello")
echo "program done"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment