From 8e8263370b51bc9b71916273e3eb956053532c4f Mon Sep 17 00:00:00 2001 From: Eugene Kabanov Date: Mon, 12 Sep 2022 15:11:13 +0300 Subject: [PATCH] Add more FutureBase helpers. (#304) --- chronos/asyncfutures2.nim | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/chronos/asyncfutures2.nim b/chronos/asyncfutures2.nim index 98e85c3..eb46e35 100644 --- a/chronos/asyncfutures2.nim +++ b/chronos/asyncfutures2.nim @@ -295,6 +295,10 @@ proc cancel(future: FutureBase, loc: ptr SrcLoc): bool = future.mustCancel = true return true +template cancel*(future: FutureBase) = + ## Cancel ``future``. + discard cancel(future, getSrcLocation()) + template cancel*[T](future: Future[T]) = ## Cancel ``future``. discard cancel(FutureBase(future), getSrcLocation()) @@ -823,7 +827,7 @@ proc oneValue*[T](futs: varargs[Future[T]]): Future[T] {. return retFuture -proc cancelAndWait*[T](fut: Future[T]): Future[void] = +proc cancelAndWait*(fut: FutureBase): Future[void] = ## Initiate cancellation process for Future ``fut`` and wait until ``fut`` is ## done e.g. changes its state (become completed, failed or cancelled). ## @@ -845,7 +849,10 @@ proc cancelAndWait*[T](fut: Future[T]): Future[void] = fut.cancel() return retFuture -proc allFutures*[T](futs: varargs[Future[T]]): Future[void] = +proc cancelAndWait*[T](fut: Future[T]): Future[void] = + cancelAndWait(FutureBase(fut)) + +proc allFutures*(futs: varargs[FutureBase]): Future[void] = ## Returns a future which will complete only when all futures in ``futs`` ## will be completed, failed or canceled. ## @@ -883,6 +890,19 @@ proc allFutures*[T](futs: varargs[Future[T]]): Future[void] = return retFuture +proc allFutures*[T](futs: varargs[Future[T]]): Future[void] = + ## Returns a future which will complete only when all futures in ``futs`` + ## will be completed, failed or canceled. + ## + ## If the argument is empty, the returned future COMPLETES immediately. + ## + ## On cancel all the awaited futures ``futs`` WILL NOT BE cancelled. + # Because we can't capture varargs[T] in closures we need to create copy. + var nfuts: seq[FutureBase] + for future in futs: + nfuts.add(FutureBase(future)) + allFutures(nfuts) + proc allFinished*[T](futs: varargs[Future[T]]): Future[seq[Future[T]]] = ## Returns a future which will complete only when all futures in ``futs`` ## will be completed, failed or canceled.