Cancels futures, with the option to interrupt running ones.
Value
cancel() returns (invisibly) the canceled Futures after
flagging them as "canceled" and possibly interrupting them as well.
Canceling a lazy or a finished future has no effect.
See also
A canceled future can be reset() to a lazy, vanilla future
such that it can be relaunched, possibly on another future backend.
Examples
## Set up two parallel workers
plan(multisession, workers = 2)
## Launch two long running futures
fs <- lapply(c(1, 2), function(duration) {
future({
Sys.sleep(duration)
42
})
})
## Wait until at least one of the futures is resolved
while (!any(resolved(fs))) Sys.sleep(0.1)
## Cancel the future that is not yet resolved
r <- resolved(fs)
cancel(fs[!r])
## Get the value of the resolved future
f <- fs[r]
v <- value(f)
message("Result: ", v)
#> Result: 42
## The value of the canceled future is an error
try(v <- value(fs[!r]))
#> Error : Future (<unnamed-3>) of class MultisessionFuture was canceled (pid 1474947) [future <unnamed-3> (361dc2a79f244d1f5411908a9e98daa1-3); on 361dc2a79f244d1f5411908a9e98daa1@hb-x1-2023<1474623> at 2026-01-16 14:52:06.255758]
## Shut down parallel workers
plan(sequential)
