Loading…
Loading…
Given a list of numbers, use a thread pool to compute the square of each number in parallel, then print the sum of the squares.
Why this is gradable. Concurrent code can legitimately produce different interleavings on every run, so this practice bank only includes problems whose correctness reduces to one deterministic final value or invariant — never a specific thread ordering. If your solution is correct, it will print the exact same output on every run, no matter how the scheduler interleaves your threads. Squaring is a pure, independent computation per element — no shared mutable state at all — so this is the simplest possible correct use of a thread pool: parallelize the independent work, then combine deterministic results.
Input: 1 2 3
Output: 14 (1² + 2² + 3² = 1 + 4 + 9 = 14)
Spawning a new OS thread per task (like the other problems in this bank do, deliberately, to expose synchronization bugs) doesn't scale to thousands of tasks and wastes resources on cheap work. A thread pool (e.g. concurrent.futures.ThreadPoolExecutor) reuses a fixed number of worker threads across many tasks — the standard real-world pattern once you're past "how do locks work" and into "how do I actually structure parallel work."
Use ThreadPoolExecutor.map (or submit + gather futures) to apply the squaring function across the input list with a small fixed number of workers, then sum the results. No locks needed here — each task is independent and only the final sum() combines results, after all tasks are done.
Line 1: space-separated integers
Print the sum of their squares.
Input (stdin)
Output
Input (stdin)
Output
Sign in to track solved problems and earn XP.