Parallel execution and thread pools
Constantine uses a reusable thread pool to run independent work in parallel. The same runtime supports small asynchronous tasks, range-based loops, reductions, and parallel cryptographic operations such as multi-scalar multiplication, pairing-group multi-exponentiation, BLS batch verification, and Ethereum KZG work. Callers create the pool, submit work through a high-level API, wait for the required result, and shut the pool down when the work is complete.
Execution model
The execution model separates the decision to expose parallel work from the cryptographic operation that consumes it. A caller supplies a Threadpool to an operation. The operation then schedules work and returns either after completion or with a Flowvar, which is a handle for a result that will become ready later.
Thread-pool lifecycle
The thread pool is the shared execution context for parallel work. Its creator acts as the root worker while other workers process queued tasks. The pool waits for all work before shutdown, so a normal lifecycle is: create, submit or call parallel work, wait, and shut down. The deeper runtime design is described in Thread-pool runtime design.
References: constantine/…/threadpool.nim• L943-1037 include/…/threadpool.h• L22-45
Task completion
Task results use Flowvar handles. spawn starts a task and can return a result handle. sync waits for that result while the waiting worker continues to process useful work when possible. syncScope gives a group of child tasks a clear completion boundary. This keeps dependent work inside the same pool instead of forcing the caller to manage individual worker threads.
References: constantine/…/threadpool.nim• L741-850 constantine/…/threadpool.nim• L897-1097
Work distribution
Constantine uses two related ways to expose work. Task parallelism creates separate units of work. Data parallelism presents an iteration range that the runtime can split as workers become available. Both forms can be nested, which lets a high-level cryptographic operation use the same pool as a lower-level loop.
Task parallelism
Task parallelism suits independent calls and pipeline stages. spawn schedules a function call and returns at once. The caller can later use sync to obtain the result, or use readiness checks when it can do other work first. A task belongs to the scope that created it, so scoped waits can cover all child tasks without tracking each task separately.
References: constantine/…/threadpool.nim• L1044-1097 constantine/…/parallel_offloading.nim• L54-289
Data parallelism
Data parallelism applies one loop body to many indexes. parallelFor starts with one range and lets the runtime split that range when idle workers need work. The split adapts to current load rather than relying only on the number of CPU cores or a fixed grain size. Nested loops use the same pool, so an inner loop does not need to create another pool.
The loop body can capture values from its surrounding scope. The examples in examples-threadpool/e03_parallel_for.nim show a plain loop, captured values, and nested loops.
References: constantine/…/threadpool.nim• L422-648 constantine/…/threadpool.nim• L1096-1132 examples-threadpool/e03_parallel_for.nim• L9-60
Reductions
A reduction combines many loop results into one value. Constantine gives each task a local accumulator, then merges the partial results through Flowvar handles. This avoids one shared lock or atomic update for every iteration. The combine operation must be associative because the runtime can choose a different split and merge shape for each run. Floating-point addition does not meet that rule exactly, so its result can vary with the split.
The reduceInto form has four roles: initialize local state, process the assigned indexes, merge remote partial results, and return the local result. The compact sum example in examples-threadpool/e04_parallel_reduce.nim shows this contract.
References: constantine/…/parallel_offloading.nim• L743-882 constantine/…/threadpool.nim• L612-648 examples-threadpool/e04_parallel_reduce.nim• L9-29
Range partitioning
Some work needs explicit chunks instead of runtime splitting. The partitioners produce balanced ranges for regular work and can keep chunks within minimum and maximum size limits. This is useful when a cryptographic routine needs predictable temporary memory or when it can process a whole chunk more efficiently than one item at a time.
The main choices are:
- Adaptive loop splitting: best when the runtime should react to current idle workers and nested work.
- Balanced number splitting: divides a range into nearly equal chunks.
- Bounded-size splitting: chooses a chunk count that keeps each chunk inside a requested size range.
The partitioner notes explain when regular cryptographic work benefits from explicit chunks and when adaptive splitting is a better fit.
References: constantine/…/partitioners.nim• L26-102 docs/threadpool-partitioners.md• L1-16 docs/threadpool-partitioners.md• L97-165
Parallel cryptographic entry points
Parallel cryptographic APIs preserve the mathematical result of their serial counterparts while dividing independent parts of the computation across the pool. They are concentrated around operations with many points, many group elements, many signatures, or large polynomial domains. Most entry points wait for all internal work before they return; some internal stages use asynchronous handles to overlap independent work.
Elliptic-curve operations
The elliptic-curve parallel API provides batch point addition and multi-scalar multiplication (MSM). MSM computes a sum of scalar-times-point terms. Constantine can expose parallelism across scalar windows, bucket work, or independent portions of the input. Batch addition selects a serial path for small inputs and uses chunked or accumulator-based work as the input grows.
These operations are the main building blocks for proof systems and commitment code. The low-level export is available through constantine/lowlevel_elliptic_curves_parallel.nim, but that module warns that low-level APIs have no stability guarantee. Protocol-facing code should use the higher-level entry points instead.
References: constantine/…/ec_multi_scalar_mul_parallel.nim• L78-132 constantine/…/ec_multi_scalar_mul_parallel.nim• L519-639 constantine/…/ec_shortweierstrass_batch_ops_parallel.nim• L27-123 constantine/lowlevel_elliptic_curves_parallel.nim• L16-55
Pairing-group operations
The pairing-group API provides parallel multi-exponentiation in 𝔾ₜ. It computes independent window products in parallel and then combines them into one result. Optional torus and endomorphism paths change the representation or reduce the scalar work, but the caller still sees one parallel operation with one final result.
The same pattern supports BLS batch verification. The verifier divides the pairing work into partial accumulators, merges those accumulators, and performs the final check. It requires input keys and signatures to satisfy the normal group checks. It also requires random bytes that an attacker cannot control for the batch blinding step.
References: constantine/…/gt_multiexp_parallel.nim• L41-101 constantine/…/gt_multiexp_parallel.nim• L283-390 constantine/…/bls_signatures_parallel.nim• L38-96 constantine/…/bls_signatures_parallel.nim• L110-182
Polynomial and KZG operations
The polynomial and KZG APIs use parallel loops for large evaluation domains and use MSM for commitment and proof work. A KZG commitment computes a commitment from a polynomial in evaluation form. Proof generation computes the evaluation and quotient polynomial before producing the group proof. Blob verification converts the blob, evaluates the polynomial, and checks the proof; batch verification also combines many verification sets with random weights.
The Ethereum-facing functions in constantine/ethereum_eip4844_kzg_parallel.nim connect these stages to blob commitments, proof generation, single-blob verification, and batch verification. A single KZG proof check remains serial in the benchmark surface because it does not expose a useful independent batch of work.
References: constantine/…/polynomials_parallel.nim• L24-97 constantine/…/kzg_parallel.nim• L30-78 constantine/…/kzg_parallel.nim• L80-229 constantine/ethereum_eip4844_kzg_parallel.nim• L125-159 constantine/ethereum_eip4844_kzg_parallel.nim• L254-422
Parallel cryptographic flow
The main cryptographic flow turns a large input into independent work, reduces the partial results, and performs a final serial step when the algorithm requires one. The following diagram shows the common shape across MSM, pairings, BLS batch verification, and KZG work.
flowchart LR
A[Input set] --> B[Prepare ranges or stages]
B --> C[Run independent work on thread pool]
C --> D[Merge partial results]
D --> E[Final group or protocol check]
E --> F[Return result]
References: constantine/…/bls_signatures_parallel.nim• L40-70 constantine/…/kzg_parallel.nim• L126-229 constantine/ethereum_eip4844_kzg_parallel.nim• L299-422
Examples and benchmarks
The examples show the runtime contract with simple arithmetic. The benchmarks show how Constantine compares serial work with parallel work on real cryptographic inputs. They are useful for learning the intended call shape and for measuring a target machine, but their timing values are not portable claims.
Thread-pool examples
examples-threadpool/e02_parallel_pi.nim demonstrates task parallelism by scheduling one result-producing task per term and syncing the returned handles. e03_parallel_for.nim demonstrates range loops, captures, and nested loops. e04_parallel_reduce.nim demonstrates local accumulators and remote-result merging. Together they form the shortest path from pool creation to the main parallel APIs.
References: examples-threadpool/e02_parallel_pi.nim• L15-35 examples-threadpool/e03_parallel_for.nim• L1-60 examples-threadpool/e04_parallel_reduce.nim• L9-34
Correctness checks
The parallel tests compare parallel elliptic-curve sums and MSM results with serial reference calculations across several input sizes and scalar or point patterns. Pairing-group tests compare parallel multi-exponentiation with a direct result. Ethereum KZG tests use protocol vectors and check both returned status and serialized outputs.
References: tests/…/t_ec_template_parallel.nim• L69-192 tests/…/t_pairing_template_parallel.nim• L49-90 tests/t_ethereum_eip4844_deneb_kzg_parallel.nim• L37-191
Performance benchmarks
The cryptographic benchmarks report average time per operation, throughput, and parallel speedup. Elliptic-curve and pairing benchmarks compare serial baselines with optimized and parallel variants. Ethereum BLS and KZG benchmarks compare serial and parallel protocol calls across batch sizes. BLS benchmarks can set CTT_NUM_THREADS; otherwise they choose the host processor count. Benchmark results depend on CPU, thread count, memory pressure, and the selected input size.
References: benchmarks/bench_elliptic_parallel_template.nim• L40-53 benchmarks/bench_elliptic_parallel_template.nim• L111-189 benchmarks/bench_gt_parallel_template.nim• L120-234 benchmarks/bench_eth_bls_signatures.nim• L191-258 benchmarks/bench_eth_eip4844_kzg.nim• L66-228
Runtime use constraints
The pool must be treated as an execution context with ownership rules, not as a general object that can move between arbitrary threads. Code that calls into a pool must follow the thread and build constraints below. These rules protect the thread-local state used by the runtime and keep parallel cryptographic calls aligned with their input contracts.
Build and ownership rules
Thread-pool code requires Nim threads to be enabled. A pool must be created and used from its creating thread. External callers must preserve that thread affinity; for example, the C header calls out thread pinning for Go and disallows moving the pool into Rust. Two Constantine pools must not be created at the same time from one thread. Other libraries may use their own pools, but mixed pools can reduce performance.
References: constantine/…/threadpool.nim• L9-10 constantine/…/threadpool.nim• L975-997 include/…/threadpool.h• L24-41
Cryptographic input rules
Parallel entry points do not remove the validation and security requirements of the serial protocol. BLS batch verification expects matching public-key, message, and signature sets with checked group elements. Its blinding input must come from a secure source that is not controlled by the attacker. KZG batch verification has the same need for attacker-independent randomness to prevent rogue linear combinations. Callers must also wait for all asynchronous work before releasing the buffers used by that work.
References: constantine/…/bls_signatures_parallel.nim• L72-96 constantine/ethereum_bls_signatures_parallel.nim• L35-88 constantine/ethereum_eip4844_kzg_parallel.nim• L299-325 constantine/ethereum_eip4844_kzg_parallel.nim• L333-422
Change checklist
When these files or sections are changed, remember to consider these:
- Changes to
Threadpool,Flowvar, or scoped waits can affect every task, loop, reduction, and protocol entry point that shares the runtime. - Changes to loop splitting or partitioner rules can alter reduction order, temporary memory needs, and the point at which a parallel cryptographic path becomes faster than its serial path.
- Changes to parallel MSM or pairing-group reduction must be checked against every caller that assumes a completed group result before serialization or a final pairing check.
- Changes to BLS or KZG batch weighting must preserve attacker-independent randomness and the matching input-set contract.
- Changes to the C thread-pool ABI must stay aligned with the Nim exports and with foreign callers that depend on thread affinity.
- Changes to the benchmark thread-count selection should be read as measurement changes, not as changes to cryptographic behavior.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| The pool is used from a thread other than its creator | Thread-local runtime state is invalid or the foreign call contract is broken | Keep calls on the creating thread; use the platform-specific thread-affinity rule for FFI callers |
| Thread-pool code is built without Nim threads | Compilation fails before parallel code can run | Enable --threads:on |
A caller shuts down or releases input storage before a Flowvar or scope is complete | A worker can read released data or a task can leak | sync each needed future or use syncScope before releasing captured data; call shutdown last |
| A reduction combines values with a non-associative operation | Results can change with task splits or worker load | Use an associative combine rule; treat floating-point sums as order-sensitive |
| BLS batch inputs have mismatched lengths or unchecked group elements | Verification returns an input or point error instead of a valid result | Validate group elements and keep each public-key, message, and signature set aligned |
| BLS or KZG batch blinding uses attacker-controlled or reused unsafe randomness | Batch algebra can admit rogue or forged combinations | Supply cryptographically secure or protocol-derived attacker-independent bytes |
| A parallel call is used for a small or low-work input | Scheduling overhead can exceed the computation time | Compare the matching serial and parallel benchmark paths for the target workload |
Key files
| File | Why to read it |
|---|---|
constantine/threadpool/threadpool.nim | Defines pool lifecycle, task completion, scoped waits, adaptive loop splitting, and the public parallel API. |
constantine/threadpool/parallel_offloading.nim | Shows how task calls, loops, captures, and reductions become scheduled work. |
constantine/threadpool/partitioners.nim | Defines balanced and bounded range partitioning for explicit chunked work. |
constantine/math/elliptic/ec_multi_scalar_mul_parallel.nim | Shows the main parallel MSM entry point and the independent work levels available in MSM. |
constantine/math/elliptic/ec_shortweierstrass_batch_ops_parallel.nim | Shows how batch curve addition chooses between serial, accumulator, and chunked paths. |
constantine/math/pairings/gt_multiexp_parallel.nim | Shows parallel multi-exponentiation in the pairing target group. |
constantine/signatures/bls_signatures_parallel.nim | Shows the batch pairing flow and its security input requirements. |
constantine/commitments/kzg_parallel.nim | Connects polynomial work and MSM to KZG commitments, proofs, and batch checks. |
constantine/ethereum_eip4844_kzg_parallel.nim | Exposes the Ethereum blob and KZG parallel operations. |
examples-threadpool/e03_parallel_for.nim | Gives a small example of range work, captures, and nested loops. |
examples-threadpool/e04_parallel_reduce.nim | Gives a small example of a local accumulator and reduction merge. |
benchmarks/bench_eth_bls_signatures.nim | Compares serial and parallel BLS batch verification across practical batch sizes. |
benchmarks/bench_eth_eip4844_kzg.nim | Compares serial and parallel Ethereum KZG operations and batch verification. |
| include/…/threadpool.h | Defines the C ABI and the ownership and thread-affinity contract for foreign callers. |