Threads and Processes Checkpoint
30 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
This checkpoint tests the whole module: threads and locks, processes and pools, executors and the GIL. Read each question, then run the code in your head.
Pick the tool first
A report job loads 20 customer records from a slow service, then runs a heavy calculation on each. The loading waits, so it fits threads. The calculation uses the CPU, so it fits processes.
Mixing is common: a thread pool for the waiting part feeds a process pool for the calculating part.
Keep shared state safe
Threads share memory, so a shared total needs a lock. Processes do not share memory, so results must come back as return values.
In both cases, sort or key results before printing.
Example 1 · Threads for loading, one place to combine
import timefrom concurrent.futures import ThreadPoolExecutor
def load(customer_id): time.sleep(0.05) # a slow service return customer_id, customer_id * 100
with ThreadPoolExecutor(4) as ex: balances = dict(ex.map(load, range(1, 6)))print(balances)print(sum(balances.values())){1: 100, 2: 200, 3: 300, 4: 400, 5: 500}
1500What this code does
- The five loads overlap, so the wait is about one load, not five.
mapreturns pairs in input order, anddict(...)builds the lookup.- Nothing is shared between jobs: each returns its own pair.
Example 2 · Processes for the calculation
from concurrent.futures import ProcessPoolExecutor
def risk_score(balance): return sum(i % 7 for i in range(balance))
if __name__ == "__main__": balances = [100, 200, 300, 400, 500] with ProcessPoolExecutor(2) as ex: scores = list(ex.map(risk_score, balances)) print(scores)[295, 594, 897, 1197, 1494]
What this code does
- The function is at module level, so it can be pickled and sent to a worker.
- The result list lines up with
balances.
If you find yourself locking a lot, return values from jobs instead and combine them in one place.
Finish up
Mark complete & continue
Next: async, await and the Event Loop