Broken counter
What's the minimum value this Python code can print:
import threading
num_threads = 5
count = 10
counter = 0
def increment(count):
for i in xrange(0, count):
global counter
counter += 1
threads = []
for i in xrange(0, num_threads):
threads.append(threading.Thread(
target=increment,
args=(count,)))
for t in threads:
t.start()
for t in threads:
t.join()
print counter
The fact that the code is in Python doesn't really matter. Basically you're given 5 threads that each increment an integer variable counter exactly 10 times. The variable isn't guarded by any lock. You can assume that reads and writes to the variable are atomic operations. What's the minimum value the counter can have after all threads finished.