Module zksync_concurrency::scope

source ·
Expand description

Implementation of Structured Concurrency (both sync and async) with cancellation, based on Golang errgroup (https://pkg.go.dev/golang.org/x/sync/errgroup). Instead of “errgroup” we use name “scope” to be consistent with std::thread::scope.

Scope represents a concurrent computation bounded by lifetime 'env. It should be constructed only via run! and run_blocking! macros. Scope consists of a tree of tasks, which are either blocking or async. You pass the root task as an argument to run!/run_blocking! and each task can spawn more tasks within this scope.

run!/run_blocking! returns only after all the tasks in the scope are completed. If any of the tasks returns an error, run!/run_blocking! returns the error of the task which failed first (all subsequent errors are silently dropped). If all the tasks succeed, the result of the root task is returned.

When the first task returns an error the scope’s context is canceled, and all the other tasks are notified (which means that they should complete ASAP). The scope can be also canceled externally if the context of the caller gets canceled. Scope can also get canceled once all the main tasks complete (see Task).

Scope tasks have access to all objects with lifetime bigger than 'env, in particular, they have access to the local variables of the caller. Scope tasks do not have access to each others’ local variables because there is no guarantee on the order in which the scope’s tasks will be terminated.

Scopes can be nested - you just need to call run!/run_blocking from within the task. Scope is an implementation of a concept called Structured Concurrency, which allows and promotes making concurrency an implementation detail of your functions. Therefore it is highly discouraged to pass &Scope as an argument to functions - if some function needs concurrency internally, it should rather run its own scope internally.

Macros§

Structs§

  • Equivalent of std::thread::ScopedJoinHandle. Allows for awaiting for task completion and retrieving the result.
  • Scope represents a concurrent computation bounded by lifetime 'env.

Functions§

  • Spawns the blocking closure f and unconditionally awaits for completion. Panics if f panics. Aborts if dropped before completion.