Coding Challenges: Multithreading
8 HackerRank-style challenges, auto-graded right in your browser —
no setup required. Write your function in the code box, then click
Run Tests to check it against a set of test cases
(including edge cases). Stuck? Every challenge has a
Show Solution reveal at the bottom. Every challenge's
output is fully deterministic — none of them depend on
unpredictable thread timing, even the ones that use threads
internally. Only uses what Chapters 1-20 have covered so far. No
import beyond
json/os/re/math/datetime/random/csv/threading/concurrent.futures.
1 Classify I/O-Bound vs. CPU-Bound Easy
Write a function classify_work_type(task_name) that returns "I/O-bound" if task_name is one of "download", "api_call", "database_query", "file_read", or "upload", and "CPU-bound" otherwise.
task_name is always a string.
classify_work_type("download") → "I/O-bound"classify_work_type("compute_primes") → "CPU-bound"
Show Solution
def classify_work_type(task_name):
io_tasks = {"download", "api_call", "database_query", "file_read", "upload"}
if task_name in io_tasks:
return "I/O-bound"
return "CPU-bound"
2 Estimate a Speedup Easy
Write a function estimate_speedup(sequential_seconds, threaded_seconds) that returns how many times faster the threaded version was, as round(sequential_seconds / threaded_seconds, 2).
threaded_seconds is always greater than 0.
estimate_speedup(6, 2) → 3.0estimate_speedup(10, 10) → 1.0
Show Solution
def estimate_speedup(sequential_seconds, threaded_seconds):
return round(sequential_seconds / threaded_seconds, 2)
3 Square Every Item Concurrently Medium
Write a function square_all_concurrently(items) that starts one thread per number in items (each thread squaring its number and appending the result to a shared list), joins every thread, and returns the results as a sorted list (sorting removes any dependence on which thread happened to finish first).
items is a list of integers, and may be empty.
square_all_concurrently([1, 2, 3]) → [1, 4, 9]
Show Solution
import threading
def square_all_concurrently(items):
results = []
threads = [threading.Thread(target=lambda n=n: results.append(n * n)) for n in items]
for t in threads:
t.start()
for t in threads:
t.join()
return sorted(results)
4 Safely Total Amounts Across Threads Medium
Write a function safe_total(amounts) that starts one thread per number in amounts, each thread safely adding its number to a shared total using a threading.Lock(), joins every thread, and returns the final total. Must return the mathematically correct sum every time, regardless of thread timing.
amounts is a list of integers, and may be empty.
safe_total([1, 2, 3, 4]) → 10safe_total([]) → 0
Show Solution
import threading
def safe_total(amounts):
total = 0
lock = threading.Lock()
def add(amount):
nonlocal total
with lock:
total += amount
threads = [threading.Thread(target=add, args=(a,)) for a in amounts]
for t in threads:
t.start()
for t in threads:
t.join()
return total
5 Does This Operation Release the GIL? Easy
Write a function gil_releases_for(operation) that returns True if operation is one of "sleep", "network_call", "file_read", "database_query", or "download" (I/O operations that release the GIL while waiting), and False otherwise.
operation is always a string.
gil_releases_for("sleep") → truegil_releases_for("tight_loop") → false
Show Solution
def gil_releases_for(operation):
io_ops = {"sleep", "network_call", "file_read", "database_query", "download"}
return operation in io_ops
6 Would a Lock Be Needed? Medium
Write a function would_lock_be_needed(threads_read, threads_write) that returns True if a lock would be needed to safely share state given threads_read threads reading and threads_write threads writing the same shared value, and False otherwise. A lock is needed whenever at least one thread writes and more than one thread (reading or writing, combined) touches the value.
threads_read and threads_write are non-negative integers.
would_lock_be_needed(2, 2) → true (multiple readers and writers)would_lock_be_needed(3, 0) → false (read-only, nothing being mutated)would_lock_be_needed(0, 1) → false (only one thread touches it at all)
Show Solution
def would_lock_be_needed(threads_read, threads_write):
total = threads_read + threads_write
return threads_write >= 1 and total > 1
7 Double Every Item Using a Thread Pool Medium
Write a function double_with_pool(items, max_workers) that uses ThreadPoolExecutor(max_workers=max_workers) as a context manager, maps a doubling function across items with .map(), and returns the result as a plain list (already in input order, since that's what .map() guarantees).
items is a list of integers; max_workers is always a positive integer.
double_with_pool([1, 2, 3, 4], 2) → [2, 4, 6, 8]
Show Solution
from concurrent.futures import ThreadPoolExecutor
def double_with_pool(items, max_workers):
with ThreadPoolExecutor(max_workers=max_workers) as pool:
return list(pool.map(lambda n: n * 2, items))
8 Combine Per-Thread Results Easy
Write a function combine_thread_results(per_thread_totals) that returns the sum of every value in the list per_thread_totals — standing in for the final "combine after every thread finishes" step of the shared-nothing pattern. Return 0 if the list is empty.
per_thread_totals is a list of integers, and may be empty.
combine_thread_results([500500, 500500, 500500, 500500]) → 2002000combine_thread_results([]) → 0
Show Solution
def combine_thread_results(per_thread_totals):
return sum(per_thread_totals)