example workers future complete

This commit is contained in:
Jaremy Creechley 2024-02-09 19:07:44 -07:00
parent 2d65587436
commit c0499f8db8
No known key found for this signature in database
GPG Key ID: 4E66FB67B21D3300

View File

@ -8,33 +8,33 @@ import taskpools
## todo: setup basic async + threadsignal + taskpools example here ## todo: setup basic async + threadsignal + taskpools example here
## ##
type var todo: Future[float]
ThreadArg = object
startSig: ThreadSignalPtr
doneSig: ThreadSignalPtr
value: float
proc addNums(a, b: float, ret: ptr ThreadArg) = proc completeAfter() {.async.} =
ret.value = a + b {.cast(gcsafe).}:
os.sleep(500) await sleepAsync(500.milliseconds)
let res = ret.doneSig.fireSync().get() echo "completing result: "
if not res: todo.complete(4.0)
echo "ERROR FIRING!"
proc addNums(a, b: float): Future[float] =
{.cast(gcsafe).}:
let fut = newFuture[float]("addNums")
todo = fut
result = fut
suite "async tests": suite "async tests":
var tp = Taskpool.new(num_threads = 2) # Default to the number of hardware threads. # var tp = Taskpool.new(num_threads = 2) # Default to the number of hardware threads.
asyncTest "test": asyncTest "test":
var args = ThreadArg()
args.startSig = ThreadSignalPtr.new().get()
args.doneSig = ThreadSignalPtr.new().get()
tp.spawn addNums(1, 2, addr args)
# await sleepAsync(100.milliseconds) # await sleepAsync(100.milliseconds)
await wait(args.doneSig).wait(1500.milliseconds) let fut = addNums(1, 3)
asyncSpawn completeAfter()
echo "\nawaiting result: "
let res = await fut
echo "\nRES: ", args.value echo "\nRES: ", res
check true check true