Exercises: Multithreading
starter.py below, then run
python3 starter.py from inside the folder you saved it
in. Every "download" or "wait" uses time.sleep() to stand
in for a slow network or disk operation — nothing here needs a real
network connection.
1 Creating and joining threads
Write square_task(n, results_list) that appends n * n to results_list. Create a thread for each of [2, 3, 4], start every thread, join every thread, then print sorted(results).
2 I/O-bound vs. CPU-bound
Write classify_work(description) returning "I/O-bound" for "downloading a file", "calling an API", or "reading from a database", and "CPU-bound" otherwise.
3 A race condition
Run the provided increment_unsafe(times) (no lock) on 4 threads and print the final, unreliable count.
4 Fixing it with a lock
Write increment_safe(times) — identical to increment_unsafe, but with the shared counter's read/write wrapped in with lock:. Confirm the final count is always exactly correct.
5 ThreadPoolExecutor.map()
Write cube(n) returning n ** 3, and run it across [1, 2, 3] using ThreadPoolExecutor(max_workers=3).map().
6 Locking a shared results list
Write add_order_total(order, totals_list, lock_obj) that safely appends sum(order) to a shared list from multiple threads.
🐞 Task 7 — Debug the Code
This is supposed to run three simulated downloads concurrently, but it calls t.join() immediately after t.start() inside the same loop, so each thread fully finishes before the next one even starts — running them one at a time instead of concurrently, defeating the entire point of threading. Find and fix it.
results = []
for name, seconds in [("a", 0.05), ("b", 0.05), ("c", 0.05)]:
t = threading.Thread(target=slow_task, args=(name, seconds, results))
t.start()
t.join()
print(sorted(results))
🐞 Task 8 — Debug the Code
This is supposed to safely increment a shared counter across 4 threads, but it reads and writes the shared counter without ever using total_lock, so it's vulnerable to the same race condition as Task 3. Find and fix it.
def increment_fixed(times):
global shared_total
for _ in range(times):
current = shared_total
time.sleep(0)
shared_total = current + 1