Pad top/bottom onto separate 64-byte cache lines, spill overflows to a global queue, and poll global every 61 ticks.
TL;DR30-second simplified summary▾
When 16 or 64 CPU cores pull lightweight tasks or coroutines from a single mutex-protected global queue, every spawn and poll triggers cache-line ping-ponging across cores—burning more cycles fighting over the lock than running actual application code.
A Chase-Lev Work-Stealing Deque gives each worker thread its own local double-ended circular buffer. The owner thread pushes and pops tasks strictly at the Bottom in LIFO order—hitting warm L1/L2 cache lines with zero locks and no CAS on the common path. Whenever another worker runs out of local work, it becomes a thief and steals from the Top of a busy worker's deque in FIFO order using a single-word Atomic Compare-And-Swap (CAS).
Stealing from the opposite end minimizes contention with the owner (who only contends with thieves when size == 1) and naturally steals the oldest, coarsest-grained fork-join subtrees. Production runtimes like Tokio, Go's G-M-P scheduler, and Java ForkJoinPool pair local deques with periodic global-queue fairness checks (1/61), randomized steal victims, and idle-core parking.
Why Global Mutex Queues Collapse & How Local Deques Scale.
Why this matters: Contrast O(cores) global lock cache-line ping-ponging against lock-free per-worker Chase-Lev deques.
Assume 32 worker threads spawn millions of sub-microsecond tasks into one shared mutex queue. Every push and pop invalidates the lock's 64-byte cache line across all 32 cores, collapsing throughput.
A Chase-Lev deque assigns one local circular buffer per worker. The owner pushes and pops at the Bottom (LIFO) for hot L1 cache locality, while idle thieves steal from the Top (FIFO) via Atomic CAS.
Why Global Mutex Queues Collapse & How Local Deques Scale
1.Zero Common-Path Locks: 95%+ of spawns and pops happen locally at the Bottom without touching any other core's cache line.
2.Coarse-Task Stealing: Stealing from the Top grabs older, larger subtrees so thieves stay busy longer without frequent steals.
3.Size==1 Tie-Breaker: Only when 1 item remains in the deque do owner pop() and thief steal() race via 1 CAS.
Per-worker Chase-Lev deques keep 95%+ of task ops lock-free at the LIFO Bottom while thieves steal FIFO from the Top.
Top/Bottom Indices, SeqCst Fence & Last-Item CAS Race.
Why this matters: Trace the exact atomic memory ordering needed so an owner pop() and a thief steal() never both claim the last task.
Each deque maintains two monotonic 64-bit indices: bottom (written only by the owner) and top (updated via CAS by thieves and last-item owner pops).
On pop(), the owner decrements b = bottom - 1 and executes a full SeqCst memory fence before reading t = top. Without that fence, CPU store-load reordering could let both owner and thief read stale indices and double-execute the last task!
Top/Bottom Indices, SeqCst Fence & Last-Item CAS Race
1.Why SeqCst Is Mandatory: On x86 TSO and ARM64, a store to bottom followed by a load of top can reorder without an explicit SeqCst fence.
2.Steal Path: A thief reads top (Acquire), fence, reads bottom (Acquire); if t < b, reads slot and tries CAS(&top, t, t+1).
3.64-Byte Padding: Pad top and bottom onto separate 64-byte cache lines to avoid false sharing.
A SeqCst fence between decrementing bottom and reading top prevents double-execution on the last-item CAS race.
Bounded Power-of-2 Chase-Lev Deque with Overflow Spillover.
Why this matters: Implement a power-of-2 masked work-stealing deque that spills excess tasks to a global queue instead of dropping.
Fixed-capacity local deques (e.g., 256 slots) avoid dynamic array resizing races and fit completely in L1/L2 cache.
class LocalWorkDeque:
def __init__(self, cap_pow2: int = 256) -> None:
if cap_pow2 <= 0 or (cap_pow2 & (cap_pow2 - 1)) != 0:
raise ValueError('Capacity must be a positive power of 2')
self.mask = cap_pow2 - 1
self.ring = [None] * cap_pow2
self.top = 0
self.bottom = 0
def push_or_spill(self, task, global_overflow: list) -> bool:
if self.bottom - self.top > self.mask:
# Spill half batch to global queue on local overflow
global_overflow.append(task)
return False
self.ring[self.bottom & self.mask] = task
self.bottom += 1
return TrueBounded Power-of-2 Chase-Lev Deque with Overflow Spillover
1.Bitmask Indexing: Power-of-2 capacity replaces slow integer division with a 1-cycle bitwise AND (bottom & mask).
2.Zero Dynamic Resize Races: Fixed 256-slot rings eliminate the complex concurrent array-reallocation reclamation needed by unbounded deques.
3.Batch Spillover: Spilling to the global queue on overflow acts as automatic load shedding to other cores.
Fixed 256-slot bitmask rings with global overflow spillover eliminate array-resize races and balance bursts.
Stealing Half-Batches & Randomized Victim Selection.
Why this matters: Amortize steal CAS overhead by stealing half the victim's deque at once and randomizing victim order.
If 31 idle cores all check Worker 0 first in fixed order [0, 1, 2...], they stampede Worker 0's top cache line.
Each thief picks a randomized starting victim (via per-thread xorshift PRNG) and steals half ((b - t + 1) // 2) of the victim's tasks in a single batch.
Stealing Half-Batches & Randomized Victim Selection
1.No Victim Stampede: Randomized coprime stride spreads 31 thieves evenly across all busy workers.
2.Half-Batch Amortization: Stealing 128 tasks in 1 CAS gives the thief plenty of local work before its next cross-core steal.
3.LIFO Fast Slot: Tokio also keeps a 1-item LIFO slot outside the deque so ping-ponging coroutines skip even local deque indexing.
XorShift victim randomization and half-batch steals cut cross-core CAS contention by an order of magnitude.
Preventing Global-Queue Starvation & Blocking-Syscall Hijacks.
Why this matters: Prevent LIFO fast-paths from starving global tasks and isolate blocking I/O onto dedicated thread pools.
Two classic bugs hit work-stealing runtimes: (1) two ping-ponging tasks keep the LIFO slot busy forever, starving the global queue; (2) a synchronous fsync() or DNS call blocks a worker thread.
Poll the global injection queue once every 61 local ticks (tick % 61 == 0) to guarantee bounded wait times. Offload blocking syscalls via spawn_blocking or sysmon handoff (Go's P detachment).
Preventing Global-Queue Starvation & Blocking-Syscall Hijacks
1.Prime Interval 61: Checking the global queue every 61st tick prevents lockstep synchronization across cores.
2.Cooperative Budgeting: A task running >128 async polls yields to the back of the queue so other tasks make progress.
3.Blocking Pool Offload: Never run synchronous disk/FFI calls on work-stealing worker threads.
61-tick global polling, 128-poll cooperative budgets, and blocking-pool offloading prevent starvation.
Zero-CPU Idle Worker Parking & Thundering-Herd Wakeup Suppression.
Why this matters: Park idle workers in epoll/futex without spinning 100% CPU while avoiding waking all 64 cores for 1 task.
Busy-spinning idle thieves burns 100% CPU and thermal-throttles active cores; waking all 64 parked cores for 1 spawned task wastes kernel futex cycles.
Track an atomic num_searching counter: cap active thieves at cores / 2, park excess idle workers on an epoll/futex condvar, and wake at most 1 parked worker when a new task is spawned (only if num_searching == 0).
Zero-CPU Idle Worker Parking & Thundering-Herd Wakeup Suppression
1.Searching Cap: Limiting concurrent thieves to cores/2 prevents idle cores from saturating memory bandwidth.
2.Single-Wakeup Invariant: Waking 1 worker when num_searching == 0 eliminates 64-thread thundering-herd futex storms.
3.Zero-Spin Idle: Idle microservices drop to ~0% CPU usage cleanly.
Capping concurrent thieves and waking 1 worker at a time eliminates idle spin and futex thundering herds.
Tracking Steal Ratios, Global-Queue Depth & Poll-Budget Preemptions.
Why this matters: Instrument worker utilization, steal success rate, global spillover, and long-poll task stalls.
Invisible blocking calls inside async tasks silently halve runtime throughput without raising CPU metrics.
Export worker_steal_count, global_queue_depth, task_poll_duration_p99_us, and budget_exhaustion_total.
Tracking Steal Ratios, Global-Queue Depth & Poll-Budget Preemptions
1.Blocking-Task Detector: A single poll() taking >1 ms flags synchronous mutexes or file I/O inside async code.
2.Steal Efficiency: High failed-steal counts with low idle parking indicate steal-backoff tuning is needed.
3.Overflow Surge Alert: Rising global_queue_depth signals tasks are spawning faster than cores can drain.
Monitoring >1 ms poll durations, steal ratios, and global-queue depth catches blocking bugs and runtime saturation.
Practice: Make the trade-off yourself.
In a Chase-Lev work-stealing deque, why does the owner push/pop from the **Bottom (LIFO)** while thieves steal from the **Top (FIFO)**?