Parallel computing: preserve identity across worker processes
并行计算基础
Run real spawn workers, combine results in input order and distinguish cancellation from terminating running work.
parallel-computingFinishing first should not change which example gets the answer
A preprocessing pipeline sends six independent jobs to workers. Small jobs may finish before large ones. If the pipeline attaches results to rows in arrival order, it can silently give a correct result to the wrong example.
Parallel computing therefore needs more than extra workers: independent work, stable identities, a defined combination rule and explicit failure handling. This chapter runs real Python worker processes, restores input order and propagates a worker exception. It makes no speedup claim from process count alone.
Concurrency means several tasks can be in progress; parallel execution means work actually overlaps in time. Two process IDs establish distinct processes, not proof that they occupied two CPU cores simultaneously. Scheduling and resource limits still matter.
Choose a decomposition before choosing a pool size
Independent tasks can carry their own identity
Our task with bound n computes the integer sum of squares below n. A closed form provides an independent correctness reference:
Each job receives an ID and bound, then returns its ID, sum and worker process ID. No task needs another task’s result. The parent maps each Future to an input position and writes the returned value there. as_completed reports completion, while that mapping preserves the data association. See the executor reference.
Processes and threads have different costs
In the CPython 3.12 runtime discussed here, the GIL limits simultaneous execution of ordinary Python code by threads in one interpreter; some native libraries release it. Threads can still be useful for overlapping I/O and share their address space. Separate processes have their own interpreters and incur startup, serialization and communication costs. Python threading
The program explicitly chooses spawn, which starts fresh interpreters. Submitted functions and arguments must be picklable, and the main module must be importable. A top-level task function plus a guarded main entry is deliberate. A function defined only in an interactive session is not the same execution environment. Multiprocessing start methods
If total useful work is W, the longest dependency chain takes L, and P identical workers are available, an idealized schedule cannot beat:
This lower bound ignores startup and communication; it is not a prediction of runtime. Tiny jobs can cost less than sending them to another process. A slow dependency chain or one oversized task can leave other workers idle. Measure the full workload, including how often a pool and its inputs are rebuilt.
Combining results is part of an AI algorithm
Some AI pipelines run independent preprocessing or model configurations. Others split samples across workers or split one model across devices. Their synchronization requirements differ.
For an objective that is the mean of independent per-example losses, evaluated at the same parameter vector, local mean gradients must be weighted by local sample counts:
With local means 2 and 6 over batches of sizes 1 and 3, the full mean is 5, not 4. This statement assumes the stated additive objective; coupled batch operations or inconsistent parameter states require separate analysis. Our executable computes independent sums, not a distributed training system.
Run importable workers and collect by identity
Save the complete program as a .py file and run it with Python 3.12. It uses only the standard library. The public function accepts up to twelve uniquely named jobs and one to four requested workers. IDs are nonempty strings of at most 40 characters. Integer bounds are limited to −100 through 200,000 before submission; the task’s nonnegative mathematical domain is checked inside the worker. Negative bounds therefore demonstrate a real remote exception. Booleans are rejected.
An empty job list returns immediately without creating a pool. Each nonempty call creates its own pool, submits all jobs, and waits for completion. The small queue is bounded here; a production stream may need backpressure instead of submitting all work at once.
from concurrent.futures import ProcessPoolExecutor, as_completed
import json
import multiprocessing
import os
def task_sum(task):
identity, n = task
if n < 0:
raise ValueError('a sum task requires a nonnegative bound')
return {'id': identity, 'sum': sum(i*i for i in range(n)), 'pid': os.getpid()}
def run_jobs(jobs, workers=2):
if type(workers) is not int or not 1 <= workers <= 4:
raise ValueError('request one to four workers')
if type(jobs) not in (list, tuple) or len(jobs) > 12:
raise ValueError('provide at most twelve jobs')
prepared = []
identities = set()
for job in jobs:
if type(job) not in (tuple, list) or len(job) != 2:
raise ValueError('each job is an identity/bound pair')
identity, n = job
if type(identity) is not str or not 1 <= len(identity) <= 40 or identity in identities:
raise ValueError('unique nonempty text identities required')
if type(n) is not int or not -100 <= n <= 200000:
raise ValueError('integer bound outside teaching resource limits')
identities.add(identity)
prepared.append((identity,n))
if not prepared:
return []
results = [None] * len(prepared)
with ProcessPoolExecutor(max_workers=workers,
mp_context=multiprocessing.get_context('spawn')) as pool:
positions = {pool.submit(task_sum, job): i for i,job in enumerate(prepared)}
try:
for future in as_completed(positions):
results[positions[future]] = future.result()
except Exception:
for future in positions:
future.cancel() # Running tasks need not be cancelled.
raise
return results
def main():
jobs = [('empty',0),('one',1),('two',2),('a',100000),('b',150000),('c',200000)]
results = run_jobs(jobs)
report = {'workers_requested':2,
'workers_observed':len({r['pid'] for r in results}),
'all_outside_parent':all(r['pid'] != os.getpid() for r in results),
'ordered_ids':[r['id'] for r in results],
'sums':[r['sum'] for r in results]}
try:
run_jobs([('bad',-1)])
except ValueError as error:
report['worker_failure'] = str(error)
print(json.dumps(report, indent=2))
if __name__ == '__main__':
main()
One actual run:
{
"workers_requested": 2,
"workers_observed": 2,
"all_outside_parent": true,
"ordered_ids": [
"empty",
"one",
"two",
"a",
"b",
"c"
],
"sums": [
0,
0,
1,
333328333350000,
1124988750025000,
2666646666700000
],
"worker_failure": "a sum task requires a nonnegative bound"
}
The six sums match the closed formula. The reported worker count is an observation from this run and can differ on another run: a requested pool size is a maximum, not a promise that every worker executes a task. All reported task processes differ from the parent. No timing measurement was used to assert acceleration.
The negative-bound job raises ValueError in a worker; future.result() raises it in the parent. On failure, the code requests cancellation for the other Futures and re-raises. Cancellation cannot stop already running work. Exiting the executor context waits for its shutdown, so this is not an immediate fail-fast or hard-timeout mechanism. The Future and shutdown contracts define those boundaries.
The checksum loop uses O(n) work per job and constant accumulator state under fixed-width arithmetic; Python’s unbounded integers add their own bit costs in a general analysis. This bounded example’s parent holds O(J) jobs, Futures and returned records. Each process also has interpreter memory, which those O(J) records do not describe.
More workers can expose hidden shared assumptions
Ordinary arguments sent to these processes do not create a shared mutable list. Large copied arrays can dominate memory and communication; shared-memory designs need ownership and synchronization rules. Returning a small result is different from repeatedly transferring full model states.
Stable task IDs also help assign reproducible random streams. A seed attached only to a worker may give different data different random draws when scheduling changes. See random seeds.
This example has no retries. Adding them requires distinguishing a failed attempt from a task whose external side effect already happened. Exactly-once behavior does not follow from a Future or a process pool. Its workers only compute values, so no external write must be undone.
The results are integer sums, avoiding floating-point reduction-order ambiguity. Parallel floating reductions can produce different low bits even when no data are lost. Choose an appropriate numerical contract and verify complete coverage: no missing, duplicated or misassigned partitions.
Check identity, aggregation and failure
- A large job submitted first finishes last. Should its result be appended to the last output row?
Answer: No. Restore the result to its original input position or key it by stable ID. Completion order is a scheduling observation, not a row identity.
- Workers report local mean gradients 2 and 6 from one and three samples. What is the combined mean under the stated additive objective?
Answer: (1×2+3×6)/4=5. Averaging the two means equally gives each worker equal weight rather than each sample equal weight.
- A Future is already running when
cancel()is called. Does cancellation terminate its worker?
Answer: No. Cancellation can fail once work is running. This program waits during executor shutdown and does not implement forced termination or a hard deadline.
- Can observing two worker PIDs prove a twofold speedup?
Answer: No. Startup, scheduling, communication and load balance determine elapsed time. Compare equivalent full workloads with a serial baseline and preserve the same result semantics.
Read execution contracts alongside algorithm assumptions
The executor documentation specifies completion, exceptions and cancellation. Multiprocessing documents process start and import requirements. The threading reference explains the CPython 3.12 GIL scope. These are prerequisites for interpreting a parallel program’s behavior; none supplies an automatic speedup guarantee.
Continue with profiling, GPU computing and vectorization. Keep data identity and combination semantics intact before optimizing worker count.
Make a prediction, then check
A task submitted first finishes last. Where does its result belong?
Learning objectives
- Preserve input identity independently of task completion order.
- Run importable spawn workers and handle remote exceptions.
- Separate worker capacity, useful speedup and aggregation semantics.
Prerequisites & connections
Explore related knowledge →References
- concurrent.futures — Launching parallel tasks — Python 3.12
Python Software Foundation - multiprocessing — Process-based parallelism — Python 3.12
Python Software Foundation - threading — Thread-based parallelism — Python 3.12
Python Software Foundation
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · Codex single-agent authored technical review: primary-source locations, derivations, literal or exact computational checks, real runtime experiments where stated, and bilingual review; not independent human or second-agent peer review.
- Four tests passed with real spawn workers, input-order restoration and propagated worker errors. Strict bilingual rendering: three formulas, six anchors and four answers.
- Single-agent authored technical review, with primary-source locations, stated assumptions and matching bilingual examples/exercises. Not independent human or second-agent review. Final publication navigation and repository checks are separate.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- concurrent.futures — Launching parallel tasks — Python 3.12 · Read process pickling/import requirements 133–134; as_completed 287–289; Future result exception propagation 220; cancellation 198 and shutdown behavior 44–51.
- multiprocessing — Process-based parallelism — Python 3.12 · Read spawn method 70–73: a fresh interpreter and necessary inherited resources; example uses a real importable file and guarded main.
- threading — Thread-based parallelism — Python 3.12 · Read CPython GIL qualification at line 20; scope is the stated Python 3.12 runtime, not every future Python build or all native libraries.
Related topics