Thread-pool runtime
The Constantine thread-pool runtime provides shared-memory parallel execution for fine-grained tasks and data ranges. It lets cryptographic code run independent work across a fixed group of workers while keeping task creation, result waits, loop splitting, and idle-worker sleep in one runtime. The parent page, parallel-execution, describes how this runtime fits into the wider parallel API; kzg-and-peerdas shows a major cryptographic workload that uses its parallel interface.
Runtime model
The runtime is a process-local group of worker threads with one work queue per worker. A caller creates the pool, submits work through the task or data-parallel API, waits for completion, and then shuts the pool down. The pool normally chooses a thread count from the available CPU resources, and callers can provide an explicit count when they need control (constantine/threadpool.nim#L975-L997, include/…/threadpool.h• L22-57).
The pool is tied to the thread that creates it. An external caller must keep using the pool from that creating thread, and it must not create two Constantine pools from the same thread at the same time. Other runtimes can coexist with it, but shared CPU resources can reduce performance (include/…/threadpool.h• L24-39).
Work submission
The task API represents an asynchronous call as a task. spawn returns a flowvar, which is the runtime's future-like handle for a task result. sync waits for that result; while it waits, the worker continues useful work instead of blocking at once. spawnAwaitable gives a waitable handle to a task that has no value result (constantine/threadpool.nim#L1060-L1095).
The runtime tracks task parentage and nested scopes. A scoped wait includes descendant tasks, not only the task that created them. This lets recursive code and nested parallel loops expose work without letting a surrounding scope finish while its descendants still run (constantine/threadpool/crossthread/scoped_barriers.nim#L15-L42, constantine/threadpool.nim#L1046-L1058).
The main task life cycle is:
- The creating worker packages the call and places it on its local queue.
- The owning worker runs local tasks in roughly last-in-first-out order.
- An idle worker steals work from another queue.
- A waiting worker first helps direct child work, then steals work or runs other available work until the flowvar is ready.
- The completed task transfers result and memory ownership to the flowvar waiter when a flowvar exists (
constantine/threadpool/crossthread/tasks_flowvars.nim#L16-L27,constantine/threadpool.nim#L694-L733,constantine/threadpool.nim#L741-L849).
flowchart TD
A[Caller or worker submits task] --> B[Task enters owning worker queue]
B --> C{Owning worker has local work?}
C -->|Yes| D[Run local task]
C -->|No| E[Steal from another worker]
E -->|Task found| D
E -->|No task| F[Sleep until work arrives]
D --> G{Task has result waiters?}
G -->|No| H[Release task]
G -->|Yes| I[Mark result ready and wake waiter]
I --> J[Waiter receives result and releases task]
References: constantine/threadpool.nim• L975-1095 constantine/…/tasks_flowvars.nim• L16-27 constantine/…/tasks_flowvars.nim• L91-109 constantine/…/scoped_barriers.nim• L15-42
Work queues
Each worker owns a growable queue. The owner adds and removes work at one end, while other workers steal from the opposite end. This reduces contention because normal local execution and stealing use different queue ends; only the last item needs a race between the owner and thieves (constantine/threadpool/crossthread/taskqueues.nim#L9-L32, constantine/threadpool/crossthread/taskqueues.nim#L50-L59).
When a worker searches for stolen work, it visits possible victims in a cheap pseudo-random order. The order does not need strong randomness. Its purpose is to spread steal attempts and avoid many idle workers contending for the same queue (constantine/threadpool.nim#L42-L47, docs/threadpool-random_permutations.md• L3-14).
References: constantine/…/taskqueues.nim• L9-32 constantine/…/taskqueues.nim• L144-213 constantine/threadpool.nim• L656-667 docs/threadpool-random_permutations.md• L3-27
Waits and idle workers
The runtime uses two kinds of wait. A worker waiting for a task uses a pool-wide backoff signal. A worker waiting for one flowvar can sleep on that task's completion signal. This distinction avoids waking every worker for a result that only one waiter needs (constantine/threadpool/crossthread/backoff.nim#L21-L46, constantine/threadpool/crossthread/tasks_flowvars.nim#L127-L157).
The pool-wide signal also reports workers that are preparing to sleep or already asleep. The data-parallel scheduler uses this count as a view of current demand. A worker wakes when new work reaches an empty queue, and pool shutdown wakes all workers after it marks them for termination (constantine/threadpool/crossthread/backoff.nim#L77-L122, constantine/threadpool.nim#L399-L418, constantine/threadpool.nim#L1014-L1033).
References: constantine/…/backoff.nim• L21-46 constantine/…/backoff.nim• L77-122 constantine/…/tasks_flowvars.nim• L138-157 constantine/threadpool.nim• L694-733 constantine/threadpool.nim• L1014-1033
Data-parallel scheduling
The parallelFor API turns an iteration range into a task. The runtime does not split the full range only once at submission time. A worker starts the range and checks whether other workers are idle. If they are, it divides the remaining iterations into balanced pieces and places the extra pieces on queues (constantine/threadpool.nim#L435-L455, constantine/threadpool.nim#L574-L610).
This is lazy splitting, meaning that the runtime delays a split until current demand makes more work useful. It avoids tying the chunk size only to the CPU count. It also supports nested loops because an inner loop can expose more work when workers are available (constantine/threadpool.nim#L435-L455). The split pieces differ by at most one iteration when the range divides evenly across the available workers (constantine/threadpool.nim#L476-L498).
flowchart LR
A[Iteration range] --> B[One initial loop task]
B --> C[Worker processes iterations]
C --> D{Idle workers detected?}
D -->|No| C
D -->|Yes| E[Divide remaining iterations into balanced ranges]
E --> F[Keep one range locally]
E --> G[Queue other ranges]
G --> H[Workers run or steal ranges]
F --> I[Loop complete]
H --> I
Static partitioning is still useful when the caller knows that work is regular. Its balanced partitioner spreads a range over a target number of chunks, with sizes that differ by at most one. Its size-priority form also keeps chunks within requested minimum and maximum bounds when possible (constantine/threadpool/partitioners.nim#L15-L24, constantine/threadpool/partitioners.nim#L26-L39, constantine/threadpool/partitioners.nim#L44-L102). Static partitioning cannot react to other system load, uneven work, or mixed-speed cores (constantine/threadpool/partitioners.nim#L15-L24).
References: constantine/threadpool.nim• L435-455 constantine/threadpool.nim• L476-610 constantine/…/partitioners.nim• L15-24 constantine/…/partitioners.nim• L26-39 constantine/…/partitioners.nim• L44-102
Reduction workloads
A parallel reduction combines local partial results into one result. Each loop task keeps its own accumulator, then merges results from ranges that other workers process. This avoids a shared lock in the main loop, but the reduction operation must be associative because the runtime can choose a different grouping of partial results. Floating-point addition can therefore produce small run-to-run changes (constantine/threadpool/parallel_offloading.nim#L803-L842).
The reduction form has four logical stages:
- Prologue: create a local accumulator with the operation's neutral value.
- Loop: process the assigned range.
- Merge: combine a remote partial result.
- Epilogue: release local state and return the partial result (
constantine/threadpool/parallel_offloading.nim#L306-L339,constantine/threadpool.nim#L612-L648).
The runtime keeps split reduction tasks in a task-local merge list. The root task waits on the final flowvar after all partial results have been merged (constantine/threadpool/crossthread/tasks_flowvars.nim#L77-L86, constantine/threadpool.nim#L637-L648).
References: constantine/…/parallel_offloading.nim• L306-339 constantine/…/parallel_offloading.nim• L803-842 constantine/…/tasks_flowvars.nim• L77-86 constantine/threadpool.nim• L612-648
CPU use and runtime boundaries
The default worker count comes from the runtime's CPU query. The query reports logical processors that the OS makes available and can account for disabled cores, but it does not see all container CPU time quotas or every cgroup restriction (constantine/threadpool/primitives/topology.nim#L15-L40, include/…/threadpool.h• L47-57). Applications can select a count through their own configuration; the examples use CTT_NUM_THREADS and otherwise use the host processor count (benchmarks-threadpool/fibonacci/threadpool_fib.nim#L38-L43, benchmarks-threadpool/black_scholes/threadpool_black_scholes.nim#L326-L341).
The runtime favors physical-core style compute use because the library's common workloads can be limited by memory bandwidth and arithmetic execution resources. It does not promise that more logical threads improve throughput. The correct count remains workload and host dependent (constantine/threadpool/primitives/topology.nim#L23-L40).
The C interface exposes pool creation and shutdown through an opaque ctt_threadpool handle. Parallel cryptographic interfaces accept that handle, so the caller controls pool lifetime while the operation uses the same worker group (include/…/threadpool.h• L22-45, include/…/ethereum_eip4844_kzg_parallel.h• L20-112).
References: constantine/…/topology.nim• L15-40 constantine/…/topology.nim• L95-130 include/…/threadpool.h• L22-57 include/…/ethereum_eip4844_kzg_parallel.h• L20-112 benchmarks-threadpool/…/threadpool_fib.nim• L38-43
Example and benchmark workloads
The benchmark set exercises both task parallelism and data parallelism. It measures wall time and, on supported systems, memory use and page faults. The examples also compare serial or OpenMP forms in selected workloads, so they show scheduler behavior rather than serve as a general performance claim (benchmarks-threadpool/matrix_transposition/threadpool_transposes.nim#L119-L225, benchmarks-threadpool/black_scholes/threadpool_black_scholes.nim#L297-L370).
| Workload family | Parallel shape | Runtime behavior exercised |
|---|---|---|
| Fibonacci and depth-first search | Recursive tasks that spawn children and wait for their results | Fine-grained task creation, stealing, nested waits, and continuation progress (benchmarks-threadpool/fibonacci/threadpool_fib.nim#L13-L21, benchmarks-threadpool/dfs/threadpool_dfs.nim#L20-L34) |
| N-queens | Recursive search with a variable number of child branches | Irregular task trees and result aggregation (benchmarks-threadpool/nqueens/threadpool_nqueens.nim#L99-L133) |
| Heat diffusion | Recursive row ranges over repeated matrix updates | Nested task waits over a regular numeric grid (benchmarks-threadpool/heat/threadpool_heat.nim#L135-L189, benchmarks-threadpool/heat/threadpool_heat.nim#L215-L227) |
| Matrix transpose | Parallel loops, nested loops, and tiled loops | Lazy range splitting, nested data parallelism, and memory-bound work (benchmarks-threadpool/matrix_transposition/threadpool_transposes.nim#L68-L104) |
| Matrix multiplication | Recursive divide-and-conquer over matrix dimensions | Recursive task trees, joins, and cache-aware work (benchmarks-threadpool/matmul_cache_oblivious/threadpool_matmul_co.nim#L102-L144) |
| Log-sum-exp and 2D histogram | Parallel loops with local partial results | Reduction and merge behavior over numeric data (benchmarks-threadpool/logsumexp/threadpool_logsumexp.nim#L198-L233, benchmarks-threadpool/histogram_2D/threadpool_histogram.nim#L173-L214) |
| Black-Scholes pricing | Repeated independent option calculations over an array | Regular data parallel work and comparison with OpenMP (benchmarks-threadpool/black_scholes/threadpool_black_scholes.nim#L202-L231, benchmarks-threadpool/black_scholes/openmp_black_scholes.nim#L216-L231) |
| Single producer and bouncing producer-consumer | One producer or a recursive producer creates many short consumer tasks | Queue pressure, tiny-task overhead, sleep and wake behavior (benchmarks-threadpool/single_task_producer/threadpool_spc.nim#L67-L73, benchmarks-threadpool/bouncing_producer_consumer/threadpool_bpc.nim#L68-L78) |
The cryptographic use case follows the same model but with larger specialized operations. Parallel KZG APIs accept the shared pool for commitment creation, proof generation, single proof checks, and batch proof checks (include/…/ethereum_eip4844_kzg_parallel.h• L20-112). See kzg-and-peerdas for the product-level role of those operations.
References: benchmarks-threadpool/…/threadpool_fib.nim• L13-21 benchmarks-threadpool/…/threadpool_dfs.nim• L20-34 benchmarks-threadpool/…/threadpool_nqueens.nim• L99-133 benchmarks-threadpool/…/threadpool_heat.nim• L135-189 benchmarks-threadpool/…/threadpool_transposes.nim• L68-104 benchmarks-threadpool/…/threadpool_matmul_co.nim• L102-144 benchmarks-threadpool/…/threadpool_logsumexp.nim• L198-233 benchmarks-threadpool/…/threadpool_histogram.nim• L173-214 benchmarks-threadpool/…/threadpool_spc.nim• L67-73 benchmarks-threadpool/…/threadpool_bpc.nim• L68-78
Change checklist
When these files or sections are changed, remember to consider these:
- Changes to task completion or flowvar ownership must preserve both the waiter wake-up path and the task memory hand-off between the runner and waiter.
- Changes to queue ownership or steal direction must preserve the single owner for local push/pop and the opposite-end contract for thieves.
- Changes to lazy loop splitting must keep loop bounds, stride, remaining-step counts, and reduction merge state consistent across split tasks.
- Changes to CPU-count detection must be checked against the C API description and the thread-count controls used by examples and external callers.
- Changes to the parallel KZG entry points must keep the shared
ctt_threadpoollifetime contract aligned with every parallel protocol caller.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A pool is used from a thread other than its creating thread | Thread-local worker state does not match the pool and external calls are unsafe | Keep pool creation and use on the same thread (include/…/threadpool.h• L24-35) |
| A caller creates two Constantine pools from one thread | The runtime's thread-local ownership assumption is violated | Use one pool per creating thread at a time (include/…/threadpool.h• L31-35) |
| A spawned result is never synchronized or a scope is left before descendants finish | Work or task storage can remain outstanding and the caller can observe incomplete work | Synchronize flowvars and use the enclosing scope or pool completion wait (constantine/threadpool.nim#L1049-L1095) |
| A reduction uses a non-associative operation | Results can change with split shape or worker timing | Use an associative fold and assess floating-point error (constantine/threadpool/parallel_offloading.nim#L823-L842) |
| A parallel loop writes shared output ranges or uses unsafe captured state | Workers race or access data whose lifetime ended before task completion | Give each task a disjoint range and capture stable shared data; the loop API rejects captured var parameters (constantine/threadpool/parallel_offloading.nim#L38-L52) |
| A benchmark treats the default CPU count as a guaranteed best setting | Logical-thread oversubscription or hidden quota limits can reduce throughput | Set the thread count for the host and workload, then compare measured results (constantine/threadpool/primitives/topology.nim#L95-L130) |
Key files
| File | Why to read it |
|---|---|
constantine/threadpool.nim | Main runtime model, worker loop, waits, lazy loop splitting, public pool and parallel APIs |
constantine/threadpool/crossthread/taskqueues.nim | Local queue and work-stealing contract |
constantine/threadpool/crossthread/tasks_flowvars.nim | Task results, completion state, memory ownership, and reduction task links |
constantine/threadpool/crossthread/backoff.nim | Idle-worker sleep and wake signals |
constantine/threadpool/crossthread/scoped_barriers.nim | Nested descendant completion model |
constantine/threadpool/parallel_offloading.nim | Task and loop API shape, captures, and reduction semantics |
constantine/threadpool/partitioners.nim | Explicit balanced partitioning options and their limits |
constantine/threadpool/primitives/topology.nim | CPU resource query and default thread-count behavior |
| include/…/threadpool.h | C-facing pool lifetime and thread-affinity contract |
| include/…/ethereum_eip4844_kzg_parallel.h | Example of a cryptographic API that receives the shared pool |
benchmarks-threadpool/fibonacci/threadpool_fib.nim | Small recursive task workload and pool setup |
benchmarks-threadpool/matrix_transposition/threadpool_transposes.nim | Nested and tiled data-parallel workload |
benchmarks-threadpool/logsumexp/threadpool_logsumexp.nim | Parallel reduction workload |
benchmarks-threadpool/single_task_producer/threadpool_spc.nim | Fine-grained producer-consumer scheduler workload |