flowchart TD A["choose a task size"] -->|small tasks| B["fixed cost per task<br/>dominates the work"] A -->|large tasks| C["fixed cost per task<br/>is amortized"] B --> D["good balance,<br/>but many steals"] C --> E["few steals, but<br/>stragglers idle cores"] D --> F["chunk to amortize,<br/>steal to rebalance"] E --> F
9.2 Task Granularity and Load Balancing
9.2.1 Motivation
Parallel work must be divided into tasks. Task size involves tradeoffs. Small tasks distribute load evenly but cost overhead per task. Large tasks amortize overhead but leave workers idle at the tail.
9.2.2 The tension
Consider distributing 1 million elements across 32 workers.
The figures below assume an overhead of 100 nanoseconds per task, for illustration.
Granule size 1: Each task holds one element, so 1 million tasks are created. At 100 nanoseconds each, the total overhead is 100 milliseconds. If each element takes 10 nanoseconds to process, the overhead is 10 times the work.
Granule size 10,000: 100 tasks of 10,000 elements each, about three per worker. Total overhead: 10 microseconds, which is negligible. But if one task takes 50 ms while the others take 10 ms, the run ends only when that task does, and workers that have run out of tasks sit idle while it finishes.
Granule size 31,250: One task per worker, a perfect split if all tasks are equal. Real workloads are not. In image processing some images are small and some are large; the worker with the small ones finishes first and idles while the others work. No granule size is right for every input.
9.2.3 Mental model
The scheduler has two competing goals:
- Amortize overhead: Group small operations into larger tasks so the per-operation cost (overhead / operations) is small.
- Balance load: Divide tasks so all workers finish at nearly the same time.
These goals conflict when task sizes vary. To achieve both, either make tasks even (static scheduling) or redistribute work dynamically (work stealing).
9.2.4 Static scheduling
Static assignment happens before execution. The scheduler divides the index range into equal chunks, by count and not by cost, and assigns one chunk per worker.
# Static scheduling: divide upfront
x <- 1:1000000
chunks <- split(x, ceiling(seq_along(x) / (length(x) / 32)))
# chunks[[1]] = 1:31250
# chunks[[2]] = 31251:62500
# ...
# Assign chunks[i] to worker iStatic scheduling has no overhead during execution. The scheduler runs once. Workers execute in parallel with no synchronization.
Static scheduling fails if task sizes are unknown or unequal.
# Static scheduling fails when sizes vary
files <- list.files("~/data")
# Some files are 1 MB, some are 1 GB
# Divide into 32 equal chunks by count, not size
# Workers that get small files finish first and idle9.2.5 Dynamic scheduling: work stealing
When tasks are unequal, work stealing rebalances. Idle workers steal tasks from busy workers.
Work stealing has overhead: atomic operations, contention, and wakeups. But it adapts to unequal task sizes.
When stealing wins:
- Task sizes vary widely (some fast, some slow)
- The variation is unpredictable (cannot be known upfront)
- Tasks are large enough that steal overhead is small relative to task size
When stealing loses:
- Tasks are tiny (nanoseconds)
- All tasks are nearly equal
- Static overhead of a single divide-and-assign is cheaper than dynamic stealing
9.2.6 Chunking strategies
Whether to steal is only half the choice. The other half is the chunk size: the number of operations grouped into one task.
Dynamic chunking with work stealing
Workers steal chunks, not individual operations. This amortizes steal overhead across the chunk.
operation_list = [op1, op2, ..., op1000000]
chunk_size = 10000 // 100 tasks, not 1000000
task_queue = []
for i in range(0, 1000000, chunk_size):
chunk = operation_list[i : i + chunk_size]
task_queue.append(chunk)
// Workers steal tasks (chunks of 10000 operations)
// Amortizes the steal cost across 10000 ops
// If a steal costs about 1 microsecond (an assumed figure),
// that is 0.1 nanoseconds per operationChunk size is a tuning parameter. Too small and steals dominate. Too large and imbalance persists.
Recursive decomposition
For divide-and-conquer problems, task creation is recursive.
quicksort(array):
if length(array) <= GRAIN_SIZE: // GRAIN_SIZE is the cutoff
return sequential_sort(array)
pivot = choose_pivot(array)
left = filter(array, < pivot)
equal = filter(array, == pivot)
right = filter(array, > pivot)
l = spawn quicksort(left)
r = spawn quicksort(right)
return concatenate(join(l), equal, join(r))If the array is no larger than GRAIN_SIZE, sort it sequentially (no parallelism). Otherwise, recurse. The recursion produces many tasks while the pieces are large and stops producing them once they are small, so a single cutoff trades overhead against parallelism. The cutoff itself still has to be chosen.
The straggler problem
Even with chunking, one task can run much longer than others. This is the straggler problem.
// 32 workers, 32 chunks
// 31 chunks complete in 10 ms
// 1 chunk (the straggler) takes 100 ms
// Total time: 100 ms
// Work done: 31 * 10 ms + 100 ms = 410 worker-ms
// Speedup over one worker: 410 / 100 = 4.1x, on 32 workersWork stealing helps: a worker that finishes early steals tasks from the straggler’s queue. But if tasks are chunked coarsely, a single large chunk dominates. Stealing does not help within a chunk.
Solutions:
- Finer chunks: Smaller chunks steal earlier and more often. But overhead rises.
- Predictive chunking: Estimate task sizes and create chunks accordingly. Hard to predict.
- Adaptive work detection: Monitor task execution time. If a task is taking longer than expected, split it. Complex.
9.2.7 Application to R
R workloads have two extremes:
Tiny vectorized operations
x <- 1:1000000
result <- x + 1 # Vectorized, no tasksVectorized R runs the loop in compiled C code, so x + 1 is one call and there are no tasks to schedule. GNU R runs that loop on one thread; only some operations, such as matrix products with a multithreaded BLAS, use several cores. Task overhead is not the problem, and load imbalance within the vector (some elements fast, some slow) is rare.
Interpreted function calls
lapply(1:1000000, function(x) x + 1)Run in parallel one element at a time, each function call would be a task. The interpreter overhead (environment setup, argument matching) is fixed per call. If the function body is tiny (one addition), overhead dominates. Chunking is necessary: batch thousands of calls into one task.
parallel::parLapply() and future.apply::future_lapply() chunk statically by default: the input is split into one chunk per worker, and chunk.size or future.chunk.size overrides that. mclapply() with its default mc.preschedule = TRUE also splits the input into one part per core, interleaved (element 1 to core 1, element 2 to core 2, and so on). The load-balancing variants are dynamic but not stealing: parLapplyLB() cuts the input into twice as many chunks as workers by default (since R 3.5.0) and hands each worker the next chunk when it finishes, and mclapply(mc.preschedule = FALSE) forks one job per element, at most mc.cores at a time. sunlight’s pmap() auto-chunks, about 16 strided chunks per worker, and then dispatches chunks on demand: an idle worker gets the next chunk instead of waiting on a static assignment.
Static chunking wins when tasks are uniform, because every dynamic dispatch costs a message round trip between processes, which is expensive next to a short R task. It loses badly when they are not, which is why pmap() chunks first to amortize that cost and then dispatches on demand to cover the skew the chunking did not predict.
9.2.8 Tradeoffs
| Strategy | Overhead | Load Balance | Best for |
|---|---|---|---|
| No chunking, one item per task | High | Best | Few large tasks of uneven cost |
| Static chunking | Low | Poor if unequal | Predictable, equal tasks |
| Dynamic work stealing | Medium | Good | Variable, unpredictable tasks |
| Recursive decomposition | Set by the cutoff | Good | Tree-like, recursive work |
9.2.9 Other systems
Cilk and Cilk Plus: Use recursive decomposition and work stealing. The programmer sets the task size by where they call cilk_spawn. Following the work-first principle of Frigo, Leiserson and Randall (1998), a spawn costs little more than a function call and the scheduling cost falls on steals, so fine-grained spawning is affordable. Thieves take the oldest frame in a victim’s deque, which near the root of the spawn tree is a large piece of work.
OpenMP: The schedule clause on a loop picks the policy. static splits the iterations into chunks and assigns them to threads round-robin before the loop runs. dynamic hands out chunks, one iteration each by default, to threads as they ask for more. guided does the same with chunks that start large and shrink in proportion to the iterations left. auto leaves the choice to the compiler and runtime, and runtime reads it from the OMP_SCHEDULE setting. None of these is work stealing in the specification, and GCC’s runtime serves dynamic and guided from one shared pool of iterations. LLVM’s runtime runs dynamic without a modifier as a stealing schedule, in which an idle thread takes part of another thread’s remaining chunks.
Rayon (Rust): Uses work stealing with adaptive splitting. A parallel iterator is first split into about as many pieces as there are threads, and a piece that gets stolen is split again. with_min_len(n) on an indexed parallel iterator stops splitting below n items, and par_chunks(n) on a slice makes each item a chunk of n elements.
Go and Java ForkJoinPool: Work stealing over small units (goroutines and ForkJoinTask objects) that cost far less to create than an OS thread. Java’s ForkJoinTask documentation gives a rough rule of thumb for granularity: a task should perform more than 100 and fewer than 10,000 basic computational steps.
Task granularity tradeoff: small tasks need many steals to balance load, large tasks have poor balance but lower steal overhead.
Further reading
- Blumofe, R. D., & Leiserson, C. E. (1999). Scheduling multithreaded computations by work stealing. Journal of the ACM, 46(5), 720-748. Proves time, space and communication bounds for randomized work stealing.
- OpenMP 5.0 specification, the worksharing-loop construct and its
scheduleclause (static, dynamic, guided, auto, runtime). https://www.openmp.org/spec-html/5.0/openmpsu41.html - Rayon documentation on chunking with
par_chunks: https://docs.rs/rayon/latest/rayon/slice/trait.ParallelSlice.html#method.par_chunks - Java ForkJoinTask documentation, including its rule of thumb for task size: https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/concurrent/ForkJoinTask.html
- Drepper, U. (2007). What Every Programmer Should Know About Memory. Section 6.4 covers multithreaded optimizations: false sharing, atomic operations and bandwidth shared between threads. https://www.akkadia.org/drepper/cpumemory.pdf
Where this appears
- sunlight pmap() auto-chunks and then dispatches chunks on demand, so granularity is chosen per call instead of being fixed by the scheduler.
- threaded-r Multi-interpreter scheduling must balance tasks across interpreters without grain sizes so large that workers idle at the tail.
- r-in-rust (rrs) rrs could use Rayon’s work stealing across interpreters, but task size (number of function calls per task) decides whether stealing pays.