Loading…
Loading…
Two producer threads split a list of items between them and push each item onto a shared queue. Three consumer threads pull items off the queue and add them to a running total. Print the final total.
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. Every item is produced and consumed exactly once, so the sum of all items is fixed no matter which consumer happens to grab which item, or in what order.
Input: 1 2 3 ... 100 (the integers 1 through 100)
Output: 5050
Producers and consumers run at different, unpredictable speeds. A thread-safe queue (like Python's queue.Queue, or BlockingQueue in Java) handles the handoff for you: put/get are already synchronized, and consumers can block until an item is available instead of busy-waiting in a loop.
total += item still needs its own lock).get timeout once producers are known to be done, or sentinel "stop" values pushed after production finishes.1def producer(chunk):
2 for item in chunk:
3 q.put(item)
4
5def consumer():
6 global total
7 while True:
8 item = q.get()
9 if item is None:
10 break
11 with lock:
12 total += itemLine 1: space-separated integers (the items to sum)
Print the total.
Input (stdin)
Output
Input (stdin)
Output
Sign in to track solved problems and earn XP.