Revizia anterioară Revizia următoare
Broken counter
What's the minimum value this 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
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 reading and writing to the variable are atomic operations. What's the minimum value the counter can have after all threads finished.