ForkUnion is a NUMA-aware fork-join thread-pool for C++, C, Rust, Zig, and Mojo — built for the tightest #pragma omp parallel for-style loops, not task queues. 🍴
It already powers NUMA-sharded vector search with USearch, LLM KV-cache and attention kernels with NumKong, and unbalanced bioinformatics workloads — thousands of combinatorial tasks per core — with StringZilla.
On the hot path it makes zero heap allocations, zero system calls, zero CAS loops, and suffers no false-sharing of cache-lines.
So dispatch latency stays flat into the hundreds of cores, precisely where task-queue runtimes like Rayon collapse and even OpenMP begins to slip.
It is also unique in parking idle workers on a hardware address monitor — x86 UMONITOR/UMWAIT, Arm WFE/WFET, RISC-V Zawrs — so a worker light-sleeps on the exact cache-line it is waiting for and the silicon wakes it the instant another core writes there, with no hot spinning and no kernel futex.
That bet compounds as sockets multiply: Intel Xeon Platinum and NVIDIA Vera pack up to 8 sockets per node, where shared CAS thrashes the interconnect and private fetch_add cursors keep synchronization off it.
One parallel-for dispatch: ForkUnion is often ~3–6× faster than OpenMP and up to ~12–16× faster than Rayon and Taskflow on many-core servers — the fork-join tax, paid once per loop, cut by an order of magnitude. Full tables ↓
It is exhaustively tested for boundary-condition scheduling with miniaturized uint8_t indices, even runs on your big-endian IBM mainframe, and ships with no_std and Miri coverage.
The core is a C++ 23 library; the C 99, Rust, Zig, and Mojo APIs bind it, and all five can pin threads to NUMA nodes or individual cores and allocate node-local memory.
Despite being far more deeply tied to hardware and the OS than most alternatives, ForkUnion runs on six operating systems — Linux, FreeBSD, Windows, macOS, Android, and iOS — including asymmetric compute and memory topologies.
Topology harvesting and thread placement work on all six; NUMA-local memory placement is implemented on Linux, FreeBSD, and Windows, and elsewhere allocation falls back to a single memory domain.
It also compiles to WebAssembly, where the pools are real in the two shapes that carry threads — Emscripten with -pthread over a shared memory, and wasm32-wasip1-threads under a runtime like Wasmtime — and collapse to the calling thread in a plain single-threaded module.
Performance
Two benchmarks measure two different things, each against the same runtimes — ForkUnion, OpenMP, Rayon, and Taskflow — on deliberately equal footing ¹.
N-body stresses the dispatch path: every task costs the same, so what is left over is scheduling latency.
Connected Components by label propagation stresses the fork-join frequency: one bandwidth-bound sweep per round until no label changes, so every round re-pays the dispatch-and-join tax.
Implementations live in bench/nbody.{cpp,rs,zig,mojo} and bench/propagation.{cpp,rs,zig,mojo}, and every binary generates bit-identical inputs from the same counter-based SplitMix64 generator, so cells compare exactly across languages.
N-Body — Dispatch Latency
Microseconds per iteration — µs ↓, lower is better — at N=512 bodies on every logical core, as static / dynamic, one fixed 30-second window per cell.
This is where fork-join runtimes genuinely differ; ➕ marks C++, 🦀 marks Rust.
| Machine | ➕ ForkUnion | 🦀 ForkUnion | ➕ OpenMP | 🦀 Rayon | ➕ Taskflow |
|---|---|---|---|---|---|
| 18× Apple M5 Pro, macOS | 32 / 37 | 28 / 32 | 115 / 137 | 222 / 339 | 83 / 94 |
| 24× Intel RPL, Windows | 148 / 143 | 112 / 91 | 360 / 627 | 151 / 151 | 812 / 1026 |
| 128× Intel SPR, Linux | 54 / 86 | 40 / 67 | 115 / 226 | 483 / 739 | 666 / 694 |
| 192× AWS Graviton 5, Linux | 47 / 136 | 42 / 137 | 266 / 216 | 490 / 580 | 602 / 639 |
Connected Components — Fork-Join Frequency
Billions of traversed edges per second — GTEPS ↑, higher is better — on a ~27M-edge "necklace" of R-MAT communities, on every logical core, as static / dynamic, one fixed 30-second window per cell.
Every pass converges in exactly 88 rounds - 88 fork-join dispatches - bit-identical in every cell and language; ➕ marks C++, 🦀 marks Rust.
| Machine | ➕ ForkUnion | 🦀 ForkUnion | ➕ OpenMP | 🦀 Rayon | ➕ Taskflow |
|---|---|---|---|---|---|
| 18× Apple M5 Pro, macOS | 29.2 / 23.5 | 19.4 / 20.2 | 23.0 / 18.3 | 23.8 / 14.6 | 21.4 / 1.3 |
| 24× Intel RPL, Windows | 10.0 / 7.2 | 5.2 / 5.5 | 11.4 / 0.1 | 9.4 / 5.2 | 6.6 / 0.7 |
| 128× Intel SPR, Linux | 46.5 / 20.9 | 65.2 / 31.4 | 28.2 / 0.4 | 8.5 / 6.5 | 25.1 / 0.5 |
| 192× AWS Graviton 5, Linux | 192.6 / 77.6 | 258.7 / 87.3 | 53.9 / 0.4 | 8.4 / 6.2 | 53.0 / 0.4 |
What the spread means - same binaries, same graph:
- The static column is the fork-join tax, compounded 88 times per pass: every runtime sweeps the identical bandwidth-bound round, so the entire spread is scheduling - dispatch latency, barrier cost, and thread placement - never arithmetic.
- The dynamic column is the claim architecture, ~92M one-vertex claims per pass: ForkUnion claims from private
fetch_addcursors, Rayon steals halves through its CAS deques, and OpenMP's and Taskflow's shared queues collapse - a 128-thread contention effect for OpenMP, whose queue survives the M5 Pro's 18 threads, while Taskflow's collapse reproduces even there. - The two ForkUnion columns are the same pool underneath: the scheduler, the graph, and the labels are bit-identical, so the gap between them - Rust ahead on SPR, behind on the M5 Pro - is compiler codegen of the compute loops, not the claims.
¹ Parity, deliberately enforced: identical
-O3+target-cpu=nativeon all sides, no LTO anywhere, unchecked hot loops in Rust, identical kernels, a 1-second warm-up, and the same one-vertex dynamic grain in every runtime. The finer per-benchmark protocol - scheduling equivalents and page-placement controls - lives in thebench/nbody.*andbench/propagation.*headers, and every setting with its default is listed in CONTRIBUTING.md.
You can rerun these benchmarks with the following commands:
cmake -B build_release -D CMAKE_BUILD_TYPE=Release -D FORKUNION_BUILD_BENCH=ON cmake --build build_release --config Release # Rust examples: plain `cargo build` grants neither flag, so parity needs both set explicitly RUSTFLAGS="-C target-cpu=native" CXXFLAGS="-O3 -march=native" cargo build --release --features benchmarks # N-body: microseconds per iteration, sustained over a fixed window (FORKUNION_TIME_LIMIT, default 10s) FORKUNION_NBODY_COUNT=512 FORKUNION_BACKEND=forkunion_static_shared build_release/forkunion_nbody FORKUNION_NBODY_COUNT=512 FORKUNION_BACKEND=taskflow_dynamic build_release/forkunion_nbody # Connected components: traversal throughput on a necklace graph; FORKUNION_PROPAGATION_COMMUNITIES controls the rounds FORKUNION_BACKEND=forkunion_static_shared build_release/forkunion_propagation FORKUNION_BACKEND=rayon_dynamic target/release/forkunion_propagation
Every port reads the same environment variables once at start; they are listed with their defaults under Benchmarks in CONTRIBUTING.md.
Quickstart
| Language | Install | Compatible with | Guide |
|---|---|---|---|
| C | CMake & prebuilt | Linux, macOS, Windows, FreeBSD, Android, iOS | c/README.md |
| C++ | CMake & headers | Linux, macOS, Windows, FreeBSD, Android, iOS | cpp/README.md |
| Rust | cargo add |
Linux, macOS, Windows | rust/README.md |
| Zig | zig fetch |
Linux, macOS, Windows | zig/README.md |
| Mojo | Pixi, from source | Linux & macOS | mojo/README.md |
ForkUnion is dead-simple to use!
There is no nested parallelism, exception handling, or "future promises"; they are banned.
A pool runs one dispatch at a time and refuses any other with the contended status, including one from inside its own callbacks.
The thread pool itself has a few core operations:
spawnto initialize worker threads, andfor_threadsto launch a blocking callback on all threads.
Higher-level APIs for index-addressable tasks are also available:
for_n- for individual evenly-sized tasks,for_n_dynamic- for individual unevenly-sized tasks,for_slices- for contiguous runs of evenly-sized tasks, one per worker.
For additional flow control and tuning, following helpers are available:
nap- to park workers on the CPU's address monitor, waking with no syscall,sleep(microseconds)- to block workers in the kernel for long idle periods, with 0 waiting for the next dispatch,terminate- to kill the threads before the destructor is called,unsafe_for_threads- to broadcast a callback without blocking, returning a generation token,unsafe_join- to block until the completion of a broadcasted generation,is_complete- to poll a generation token for completion without blocking.
Every dispatch is identified by a generation token.
On caller_exclusive_k pools you can dispatch, overlap your own work, poll is_complete, and join - the classic poll-then-join pattern.
On caller_inclusive_k pools the calling thread owes one slice of the work, which only runs inside unsafe_join, so completion can't be reached by polling alone.
The same rule shapes the RAII guard returned by for_threads and, in C++, the for_n family: the workers start at the guard's construction on every pool, and on inclusive pools the caller's own slice runs at join or destruction.
On caller_exclusive_k pools thread 0 may also fork from inside its own slice, at any depth: such a fork waits for every other slice of the one enclosing it, runs on all threads, and returns complete.
So unsafe_for_threads can hand a whole multi-step call to thread 0, which forks the rest of the pool as it goes, while the caller only polls a status word the call stores at its end.
That is how one manager thread keeps several exclusive pools busy with no queue and no extra thread.
A join on such a pool waits for whatever dispatch runs, since the call may end before its submitter stores the token.
Alternatives & Differences
Most "thread-pools" are not thread-pools at all, but task-queues - think a std::queue<std::function<void()>> behind a std::mutex, executing each heap-allocated task on whatever core the OS scheduler picks.
That shape is what most alternatives are built around, and it is the wrong shape for a tight parallel for:
- Modern C++:
taskflow/taskflow,progschj/ThreadPool,bshoshany/thread-pool - Traditional C++:
vit-vit/CTPL,mtrebi/thread-pool - Rust:
tokio-rs/tokio,rayon-rs/rayon,smol-rs/smol - Zig:
std.Io.Group, which replaced the removedstd.Thread.Poolin 0.16
Reach for ForkUnion when you have data-parallel loops, bulk-synchronous phases, or NUMA-sharded scans, and you want them to dispatch in nanoseconds with neither an allocator nor the kernel on the hot path. Reach for something else when you need task graphs, async I/O, futures and promises, work that outlives its scope, or nested parallelism — Taskflow, Tokio, and oneTBB are built for exactly that, and ForkUnion deliberately bans it.
The trade-offs line up like this, verified against each project's own source and documentation:
| Property | ForkUnion | OpenMP | Rayon | Taskflow | oneTBB |
|---|---|---|---|---|---|
| Hot-path heap allocations | None | ≈ None¹ | Per spawned task² | Per task node | Per task, pooled |
| Syscalls to dispatch | None | Spin, then futex | Spin/yield, then futex | Spin, then futex | Spin, then futex |
| Dynamic-schedule primitive | fetch_add cursors |
CAS retry loop³ | CAS deque⁴ | CAS deque⁴ | CAS deque⁴ |
| NUMA pinning & local allocators | Yes | Yes⁵ | No | No⁶ | Partial⁷ |
| Hardware timed-wait | Yes | x86 only, opt-in⁸ | No | No | No |
| Languages | C++ · C · Rust · Zig · Mojo | C · C++ · Fortran | Rust | C++ | C++ |
| Design center | Fork-join loops | Loops + tasks | Stealing tasks + iterators | Task-graph DAG | Stealing tasks |
¹ OpenMP reuses a persistent thread team, so a repeated
parallel forover a fixed-size team does not re-create it; the per-region worksharing descriptor is reused but not provably allocation-free on every path. ² Rayon keepsjoinand parallel-iterator jobs on the stack, butscope/spawnheap-allocate one job per task, and the Chase-Lev deque grows on the heap under deep nesting. ³ libgomp and libomp hand outschedule(dynamic)iterations with an atomic fetch-add plus a CAS retry loop. ⁴ Rayon, Taskflow, and oneTBB all steal through a Chase-Lev deque, whose steal path is a CAS. ⁵OMP_PROC_BIND/OMP_PLACESpin threads, and the OpenMP 5 allocator and memory-space API places memory. ⁶ Taskflow exposes only a manualWorkerInterfacehook for affinity, nothing automatic. ⁷ oneTBB pins threads to a NUMA node viatask_arenaconstraints, but does not place memory locally for you. ⁸ Only LLVM/Intellibompissues x86UMONITOR/UMWAIT, gated behindKMP_USER_LEVEL_MWAITand off by default; there is no ArmWFETor RISC-VZawrspath in any OpenMP runtime.
Locks & Mutexes
Unlike std::atomic, std::mutex can fall into a system call, and it can be expensive to acquire and release.
Its implementations generally have 2 executable paths:
- the fast path, where the mutex is not contended, where it first tries to grab the mutex via a compare-and-swap operation, and if it succeeds, it returns immediately.
- the slow path, where the mutex is contended, and it has to go through the kernel to block the thread until the mutex is available.
On Linux, the latter translates to "futex" "system calls", which is expensive.
fair_mutex in forkunion/locks.hpp reaches that slow path only after a short spin.
It is a ticket lock: callers enter in the order they arrived, wait through one of the busy-waiting wrappers, and park on a futex after about 64 capped waits; unlock makes the system call only when someone parked.
fair_mutex_t takes preferred_yield_t and preferred_atomic_ref, a unit compiled per CPU class names fair_mutex<waiter, reference>, and both work with std::lock_guard and std::unique_lock.
Anything that waits for a lock takes it, while spin_mutex_t is left for try-only claims.
Memory Allocations
C++ has rich functionality for concurrent applications, like std::future, std::packaged_task, std::function, std::queue, std::condition_variable, and so on.
Most of those, I believe, are unusable in Big-Data applications, where you always operate in memory-constrained environments:
- The idea of raising a
std::bad_allocexception when there is no memory left and just hoping that someone up the call stack will catch it is not a great design idea for any Systems Engineering. - The threat of having to synchronize ~200 physical CPU cores across 2-8 sockets and potentially dozens of NUMA nodes around a shared global memory allocator practically means you can't have predictable performance.
As we focus on a simpler concurrency parallelism model, we can avoid the complexity of allocating shared states, wrapping callbacks into some heap-allocated "tasks", and other boilerplate code.
Less work - more performance.
Atomics & CAS
Once you get to the lowest-level primitives on concurrency, you end up with the std::atomic and a small set of hardware-supported atomic instructions.
Hardware implements it differently:
- x86 is built around the "Total Store Order" (TSO) memory consistency model and provides
LOCKvariants of theADDandCMPXCHG, which act as full-blown "fences" - no loads or stores can be reordered across it. - Arm, on the other hand, has a "weak" memory model and provides a set of atomic instructions that are not fences, that match the C++ concurrency model, offering
acquire,release, andacq_relvariants of each atomic instruction—such asLDADD,STADD, andCAS- which allow precise control over visibility and order, especially with the introduction of "Large System Extension" (LSE) instructions in Armv8.1. - WebAssembly with a shared memory has its own
i32.atomic.rmw.add,i32.atomic.rmw.cmpxchgand kin, which the engine compiles to the host's atomic instructions; a module without shared memory runs one thread, so its atomics compile to plain loads and stores.
In practice, a locked atomic on x86 requires the cache line in the Exclusive state in the requester's L1 cache. This would incur a Read-for-Ownership coherence transaction if some other core had the line. Both Intel and AMD handle this similarly.
It makes Arm and Power much more suitable for lock-free programming and concurrent data structures, but some observations hold for both platforms. Most importantly, "Compare and Swap" (CAS) is a costly operation and should be avoided whenever possible.
On x86, for example, the LOCK ADD can easily take 50 CPU cycles, being 50× slower than a regular ADD instruction, and an uncontended LOCK CMPXCHG costs about the same.
Once contention rises, the CAS falls behind, amplified by its "failure" rate, particularly when the value being compared has already changed.
That's why, in the "dynamic" mode, threads claim tasks with fetch_add on private per-thread cursors rather than a CAS loop.
A dispatch does take one compare-and-swap to claim the pool, and never retries it: a claim that loses is refused rather than repeated.
Atomic References
forkunion/atomics.hpp replaces std::atomic_ref with references that spell each operation as the one instruction a CPU has for it, picked by capability bit at runtime rather than by the translation unit's -march.
Besides the standard operations, every reference offers the verbs the standard lacks:
fetch_add_if_at_mostandfetch_sub_if_at_least: onecmpccxaddon x86, a compare-exchange loop elsewhere;fetch_maxandfetch_min: oneldsmax,ldumaxoramomaxon Arm and RISC-V;- no-return
store_add,store_sub,store_max,store_min,set_bits,clear_bitsandflip_bits:staddand kin on Arm,amoaddintox0on RISC-V, RAO-INTaaddand kin for relaxed orders on x86 parts that implement it, and, opt-in throughppc64_amo_atomic_ref,stwatandstdatat the memory controller for relaxed orders on POWER9 and newer.
On an M5 Pro the Arm references run 5x faster than a baseline build's exclusive loops uncontended, and 3-4x faster with 18 threads on one word.
A no-return add may complete away from the core, so a relaxed one carries nothing to a later release: publish through it with release, as the far memory model in verification/ checks.
Alignment & False Sharing
The thread-pool needs several atomic variables to synchronize the state.
If those variables are located on the same cache line, they will be "falsely shared" between threads.
This means that when one thread updates one of the variables, it will invalidate the cache line in all other threads, causing them to reload it from memory.
This is a common problem, and the C++ standard recommends addressing it with alignas(std::hardware_destructive_interference_size) for your hot variables.
There are, however, caveats.
The std::hardware_destructive_interference_size is generally 64 bytes on x86, matching the size of a single cache line.
But in reality, on most x86 machines, depending on the BIOS "spatial prefetcher" settings, will fetch 2 cache lines at a time starting with Sandy Bridge.
Because of these rules, padding hot variables to 128 bytes is a conservative but often sensible defensive measure adopted by Folly's cacheline_align and Java's jdk.internal.vm.annotation.Contended.
Pro Tips
Topology
A machine is described along two independent axes. A compute domain is a bindable group of cores sharing a Quality-of-Service class and locality — it is what a pool spawns onto, and the index a worker callback receives. A memory domain is a bank of memory with its own capacity and access cost — it is what the allocator targets, may be cpuless like a CXL expander, and may serve several compute domains at once. The axes stay separate because they don't line up: performance and efficiency cores often share one memory controller, and equally-fast cores are often split across cache clusters or sockets.
Each axis carries a level, a dense ordinal grouping domains of like performance.
Levels can be fewer than domains, since several domains may share one, and the two axes count in opposite directions: compute levels grow with performance, memory levels grow with distance, placing HBM below DDR and CXL above.
Two objects split the answers by provenance, not by axis: a Topology holds what the platform declares — domains, cores, QoS classes, volumes, on both axes — while a Fabric holds what ForkUnion observes: per-edge latencies, bandwidths, and distances, and the per-medium tiers derived from them.
The pipeline is harvest all the way down: a Topology harvests the declared structure from the OS and stays immutable, a pool spawns on it, and a Fabric then harvests the observed performance from the silicon through that pool's pinned workers, pointer-chasing and streaming every reachable edge.
A memory level is a property of the medium, independent of the querying core: it keys on the best bandwidth any initiator sustains to the pool, ties split by the best latency, so a 3 TB/s HBM pool outranks DDR even at equal latency.
| Compute axis | Memory axis | |
|---|---|---|
| Count domains | compute_domains_count |
memory_domains_count |
| Count levels | compute_levels_count |
memory_levels_count |
| Level of a domain | compute_level_in |
memory_level_in |
| Faster means | higher | lower |
Names are spelled here as in Rust, which Mojo matches; C prefixes them with fu_, and Zig spells them in camelCase.
Rust, Zig, and Mojo all carry the domain coordinates as distinct types — ComputeDomain, MemoryDomain, and MemoryDomainId — while C passes plain indices.
Domain counts and compute levels answer from the Topology; memory levels and the per-edge magnitudes answer from a harvested Fabric, which C prefixes with fu_fabric_.
Beyond the level ordinals, two magnitudes describe a compute domain, both best-effort.
compute_capacity_in forwards the kernel's own rating of a core, read from /sys/devices/system/cpu/cpuN/cpu_capacity, normalized so the fastest core on the machine reads 1024.
Linux publishes that file on arm64 and on Intel hybrids, and nothing like it exists on Windows or Apple, which read 0.
A kernel that rates every core alike rates nothing, so a tie also reads 0; Linux then splits the classes by their core PMUs, cpu_core and cpu_atom on Intel hybrids.
compute_cache_bytes_per_core_in reports each logical core's share of the L2 serving a domain: one instance's bytes over the cores sharing it.
It is enumerated exactly rather than measured — from the per-core cache hierarchy in sysfs on Linux, CPUID leaves elsewhere on x86, sysctl on Apple, and the cache relationships on Windows.
Domains of identical throughput can sit behind very differently sized caches, so neither value follows from the other.
Treat both as hints, present only where the hardware volunteers them, and never as a number a program requires.
The memory axis carries its own magnitudes, all answered by the harvested Fabric.
memory_distance gives the relative cost of reaching a memory domain from a compute domain — 10 for local, higher for remote, on ACPI SLIT's scale but from measured ratios — while memory_bandwidth and memory_latency give the observed saturated read bandwidth and dependent-load latency per edge.
Back on the Topology, volume_ram and volume_ram_in report installed RAM, total or per domain, while huge_pages_count_in and volume_huge_pages_in report the free huge pages a domain can still back an allocation with, as a count or in bytes, and huge_pages_count and volume_huge_pages total them.
Like the compute magnitudes, these are best-effort: fabric queries read 0 before a harvest or on edges no pinned worker could reach.
Finally, local_memory_of bridges the axes, naming the memory domain a given compute domain should allocate from.
Where no topology is harvested, every query degrades to a single compute domain and a single memory domain rather than failing, so these loops need no conditional compilation.
NUMA
Placing memory on a chosen domain is implemented on Linux via the mbind syscall, on FreeBSD via domainset policies, and on Windows via VirtualAllocExNuma, and degrades to a single domain elsewhere.
The manual two-vector sharding of the C++ guide is what the symmetric allocators automate: symmetric_memory_allocator_t - fu_allocate_symmetric in C - maps one virtual range striped a slice per memory domain, and Rust, Zig, and Mojo wrap it as ShardedArray<T>, one shard per domain, and ReplicatedArray<T>, a full copy per domain for read-mostly data.
To place and coordinate pools by hand, spawn_on - fu_pool_spawn_on in C - pins a pool to a single compute domain, while locate_thread_in and threads_count_in map a global thread index to its domain and count the workers living there.
Safety & Logic
There are only 3 core atomic variables in this thread-pool, plus 1 private claim cursor per worker for dynamically-stealing tasks.
Let's call every invocation of a for_* API - a "fork", and every exit from it a "join".
| Variable | Users Perspective | Internal Usage |
|---|---|---|
mood |
Spin, sleep, or stop the pool | Tells workers to spin, sleep, or exit the loop |
epoch |
Odd while a fork runs, even if idle | Tells workers to wake up on new forks |
threads_to_sync |
Contributors still running this fork | Claimed from zero by a dispatch, last one steps epoch |
claim.next |
One worker's stealable cursor | Next task in that worker's slice |
The next task for for_n_dynamic calls is drained by neighbors from claim.next in coprime order once their own slice runs dry, each thread overshooting a cursor by at most one.
Why don't we need atomics for "total_threads"?
The only way to change the number of threads is to terminate the entire thread-pool and then spawn it again.
Either of those operations can only be called from one thread at a time and never coincide with any running tasks.
That is the caller's contract; the pool does not enforce it.
Why don't we need atomics for a "job pointer"?
Only one dispatch holds the pool at a time: it claims the pool by exchanging threads_to_sync from zero, and any other dispatch, nested or concurrent, is refused.
During its update of the fork state, the workers are asleep, spinning on old values of epoch and mood.
They only wake up and access the new state once epoch turns odd, ensuring safety.
How do we deal with overflows and SIZE_MAX-sized tasks?
The library avoids saturating arithmetic entirely.
To test the consistency of arithmetic, the C++ template class can be instantiated with a custom index_t, such as std::uint8_t or std::uint16_t.
In the former case, no more than 255 threads can operate, and no more than 255 tasks can be addressed, allowing us to easily test every weird corner case of [0:255] threads competing for [0:255] tasks.
Why not reimplement it in Rust?
The original Rust implementation was a standalone library, but in essence, Rust doesn't feel designed for parallelism, concurrency, and expert Systems Engineering. It enforces stringent safety rules, which is excellent for building trustworthy software, but realistically, it makes lock-free concurrent programming with minimal memory allocations too complicated. Now, the Rust library is a wrapper over the C binding of the C++ core implementation.
Build Variants
ForkUnion is a header-only C++ library and one translation unit, so its smallest and largest builds sit close together.
- Header-only.
forkunion::headercompiles into the consumer's own translation units, with the waiters and atomics the consumer's-marchpromises. It has no library of its own and links only system ones: threads,libatomicwhere atomics aren't built in, andsynchronizationandadvapi32on Windows. - Pre-compiled.
forkunion::staticandforkunion::sharedbuildsrc/forkunion.cppbehind thefu_*C ABI and pick waiters at run time, andforkunion::cppwraps them for C++. They add one small library to build and link;forkunion::abiis the C header alone. - Portable.
FORKUNION_PORTABLE=ONturns every optional facility off, leaving a pool with no topology, memory placement or thread affinity. - Facilities.
FORKUNION_WITH_TOPOLOGY,FORKUNION_WITH_PLACE_MEMORY_ON_DOMAIN,FORKUNION_WITH_PLACE_HUGE_PAGES_ON_DOMAINandFORKUNION_WITH_PLACE_THREADS_BY_AFFINITYeach takeAUTO,ONorOFF. None adds a system dependency: Linux topology comes from sysfs and placement callsmbindby syscall number, solibnumais never needed. - Dispatch.
FORKUNION_MULTIVERSIONEDkeeps every waiter and atomic the toolchain compiles, or only those the-marchfloor implies, as below.
Every kernel and ISA facility the library uses is detected by default.
CMake pins the four kernel facilities with an AUTO/ON/OFF tri-state like -D FORKUNION_WITH_PLACE_MEMORY_ON_DOMAIN=ON or -D FORKUNION_WITH_PLACE_THREADS_BY_AFFINITY=OFF.
Finer preprocessor gates - like the cache-line hints FORKUNION_WITH_DEMOTE_CACHE_LINES, which pushes a just-written line away from the core via x86 CLDEMOTE or Arm DC CVAC, and FORKUNION_WITH_PROMOTE_CACHE_LINES, which pulls a line in with write intent via x86 PREFETCHW, Arm PRFM PSTL1KEEP, or RISC-V prefetch.w - accept the same overrides as compile definitions.
Call fu_comptime_capabilities() to see what survived the build, fu_runtime_capabilities() to see what the machine underneath actually offers, and fu_name_capabilities() to render either mask as text - every binding exposes the same trio, Rust and Mojo spelling it runtime_capabilities() and Zig runtimeCapabilities with runtimeCapabilitiesString to render, alongside a version accessor: fu_version_major/_minor/_patch in C, version() in Rust, Zig, and Mojo, and the FORKUNION_VERSION_* macros in C++.
Every all-caps name starts with the full project name, FORKUNION_.
A trailing _ marks a name as internal: it may change in any release, and nothing outside this repository may define or test it.
A name without it is a public contract, either a switch you may set or a value you may read.
| Family | Form | Example |
|---|---|---|
| ISA capability bit | FORKUNION_TARGET_<CAPABILITY> |
FORKUNION_TARGET_X8664_PAUSE |
| Dispatch mode | FORKUNION_RUNTIME_DISPATCH |
|
| Optional facility | FORKUNION_WITH_[<OS>_]<FACILITY> |
FORKUNION_WITH_TOPOLOGY |
| Permission for a liberty | FORKUNION_ALLOW_<LIBERTY> |
FORKUNION_ALLOW_UNSAFE |
Every name in these families is always defined, as 0 or 1, and tested with #if.
Multiversioned and Monoversioned Builds
ForkUnion compiles in one of two shapes, picked by FORKUNION_MULTIVERSIONED.
- Multiversioned builds are for distributing to a diverse fleet. One binary serves every machine, because each pool picks its waiter and atomics from what the running CPU offers. This is the default, and the shape of the Rust crate and the Zig and Mojo packages.
- Monoversioned builds are for high-velocity environments of identical machines.
They compile one waiter and one atomic reference, the best that machine runs, so builds are much shorter and binaries much smaller.
Their floor is that machine's
-march, so they run only on that kind of machine and its successors. - The switches.
FORKUNION_MULTIVERSIONED=OFFpicks the second shape andFORKUNION_MARCHnames its CPU floor. Thexeon4_hopper,xeon6_blackwell,grace_hopper,vera_rubinandvenice_mi450presets spell whole machines.
A monoversioned build keeps only the capabilities its floor implies or a preset vouches for, so its waiters and atomic references are fixed to the target.
ForkUnion keeps its own names for the six words the kernel libraries dispatch by.
Each capability is a probe in cmake/forkunion_probes.cmake, a try_compile of its source under probes/, and a target in its FORKUNION_TARGET_* macro.
A monoversioned build keeps only the targets FORKUNION_MARCH implies, as probes/implied.cpp asks the preprocessor.
The targets left on are what the build compiled, and preferred_yield_t, preferred_atomic_ref and preferred_cache_hints_t are the compile-time pick among them.
cpu_capabilities() answers detected, and a pool's allowed mask, intersected with it at spawn, is what that pool has enabled.
Testing & Benchmarking
How the suites are laid out, the settings they read, and how to write a case are described under Test Suites in CONTRIBUTING.md; this section lists the commands for each toolchain.
Toolchain floors, never caps.
The header and the pre-compiled libraries need a C++23 compiler: GCC 15, Clang 22 with libstdc++ 15 or libc++ 22, Xcode 26 or VS 2026.
Building from source needs CMake 4.3, which pip install cmake provides where the system package is older.
The C ABI needs C99, and the build tooling Rust 1.100, Zig 0.16, and Mojo 1.2.
To run the C++ tests, use the CMake presets CI uses; cmake --list-presets shows the ones this machine can build:
cmake --workflow --preset release # configure, build, and run every test cmake --workflow --preset asan # or `tsan`
For C++ debug builds, consider using the VS Code debugger presets or the following commands:
cmake --preset debug && cmake --build --preset debug build_debug/forkunion_test # run a single test executable
To cross-compile for WebAssembly, pick the preset for the shape you need, and ctest runs the binaries through Node or Wasmtime:
cmake --preset wasm32_emscripten # one thread, loads in any page cmake --preset wasm64_emscripten # shared memory and 64-bit addressing cmake --preset wasm32_wasi_threads # wasi-threads under Wasmtime cmake --build --preset wasm64_emscripten && ctest --preset wasm64_emscripten
The wasm32 module has one thread, so its pool spawns caller-inclusive and only its C test runs there; the other two shapes run the C++ and C tests, minus the stress cases.
To cross-compile for Android, point the android_arm64 preset at the NDK's toolchain file and pick an ABI; the binaries only compile, since they need a device to run:
export CMAKE_TOOLCHAIN_FILE=$ANDROID_NDK_HOME/build/cmake/android.toolchain.cmake cmake --preset android_arm64 -D ANDROID_ABI=arm64-v8a -D ANDROID_PLATFORM=28 # or armeabi-v7a cmake --build --preset android_arm64
Android builds need NDK r28 or newer, the first with libc++ 19 and its std::atomic_ref, and CI builds in the FatWheels android image with NDK r29.
Machine-specific settings, like a compiler path, belong in an untracked CMakeUserPresets.json.
To run static analysis:
sudo apt install cppcheck clang-tidy cmake --build build_debug --target cppcheck # detects bugs & undefined behavior cmake --build build_debug --target clang-tidy # suggest code improvements
No packages are needed for NUMA or Huge Pages, on any distribution.
The topology is read from /sys/devices/system/node, pages are placed with the mbind syscall, and huge pages are requested with mmap(MAP_HUGETLB) — all kernel interfaces, so a build picks up whatever the machine it runs on offers rather than whatever the machine it was compiled on had installed.
Neither libnuma nor libhugetlbfs is linked; ld.hugetlbfs remaps a program's own text segment, which is a different feature entirely.
Huge pages do have to be reserved before they can be placed, which is a runtime knob rather than a build dependency:
cat /sys/kernel/mm/hugepages/hugepages-2048kB/nr_hugepages # what exists now echo 1024 | sudo tee /sys/devices/system/node/node0/hugepages/hugepages-2048kB/nr_hugepages
To build with an alternative compiler, like LLVM Clang, use the following command:
sudo apt-get install libomp-22-dev clang-22 # OpenMP version must match Clang
cmake -B build_debug -D CMAKE_BUILD_TYPE=Debug -D CMAKE_CXX_COMPILER=clang++-22 -D FORKUNION_BUILD_TEST=ON
cmake --build build_debug --config Debug
build_debug/forkunion_testOr on macOS with Homebrew's LLVM Clang:
brew install llvm@22
cmake -B build_debug -D CMAKE_BUILD_TYPE=Debug -D CMAKE_CXX_COMPILER=$(brew --prefix llvm@22)/bin/clang++ -D FORKUNION_BUILD_TEST=ON
cmake --build build_debug --config Debug
build_debug/forkunion_testFor Rust, use the following commands to verify no_std compatibility:
cargo build --lib --no-default-features --release cargo build --lib --no-default-features --features place-memory-on-domain --release cargo doc --lib --no-default-features --no-deps
Verify the tests pass:
cargo test --lib --release cargo test --doc --release cargo test --lib --features place-memory-on-domain --release
Rust provides a lot of tooling for concurrency testing, like Miri and Loom. Most of it, however, is not applicable in this case, as the core logic is implemented in C++.
To automatically detect the Minimum Supported Rust Version (MSRV):
cargo +stable install cargo-msrv cargo msrv find --ignore-lockfile
For Zig, use the following commands:
zig build test --summary all # run tests zig build -Dplace-memory-on-domain=true # require NUMA-aware allocations (Linux) zig build -Dportable=true # STL thread pool only # Run benchmarks from the `bench` directory cd bench zig build -Doptimize=ReleaseFast FORKUNION_NBODY_COUNT=512 FORKUNION_BACKEND=forkunion_static_shared ./zig-out/bin/forkunion_nbody FORKUNION_BACKEND=forkunion_static_shared ./zig-out/bin/forkunion_propagation
They read the same environment variables as the C++ and Rust benchmarks, through bench/harness.zig.
For Mojo, every task compiles the C++ core first and installs it where dlopen will find it:
pixi run test # the binding's test suite, via `std.testing.TestSuite` pixi run -e benchmarks nbody # dispatch overhead, all-to-all pixi run -e benchmarks propagation # fork-join frequency, bit-identical to the sibling ports
The benchmarks sit in their own environment because their baseline needs max, which the binding itself never does.
Both take the same environment variables as the other ports, the four forkunion_{static,dynamic}_{shared,replicated} cells, and a max_parallelize baseline:
FORKUNION_NBODY_COUNT=512 FORKUNION_BACKEND=forkunion_static_replicated pixi run -e benchmarks nbody
FORKUNION_BACKEND=max_parallelize pixi run -e benchmarks propagation
FORKUNION_PROPAGATION_CHECK=1 pixi run -e benchmarks propagation # converge serially too, and fail on any disagreementThe suite's own per-test durations are not wall clock — a pool's workers busy-wait, and the runner's clock counts that — so time the process rather than trusting them.
pixi run -e portable test # the STL thread pool only pixi run -e numa test # require NUMA-aware allocations mojo format mojo/forkunion/*.mojo test/*.mojo bench/*.mojo # width pinned in pyproject.toml
Experimental Parts
Experimental parts work today. What we reserve is the right to change them before the final release: their ABI, what the default binaries include, the compilation matrix, and the set of kernels and backends.
- The
UMWAITwaiter.x86_tpause_tparks a worker withUMONITORandUMWAITon x86 CPUs with WAITPKG. - NUMA placement.
FORKUNION_WITH_PLACE_MEMORY_ON_DOMAIN, huge pages on a domain and the per-platform*_numa_allocator_tallocators run on Linux, FreeBSD and Windows only.
Citation
If ForkUnion helps your research or product, please cite it:
@software{Vardanian_ForkUnion, author = {Vardanian, Ash}, title = {{ForkUnion: NUMA-Aware Fork-Join with No Allocations, Syscalls or CAS Loops, Parking Workers on Address Monitors}}, doi = {10.5281/zenodo.21472185}, url = {https://github.com/ashvardanian/ForkUnion}, license = {Apache-2.0} }
A machine-readable CITATION.cff is provided at the repository root.
License
Licensed under the Apache License, Version 2.0.
See LICENSE for details.