Atenţie! Aceasta este o versiune veche a paginii, scrisă la 2012-08-22 21:16:14.
Revizia anterioară   Revizia următoare  

broken multi threaded counter

Cosmin
Cosmin Negruseri
23 august 2012

Given 5 threads that each increment an integer counter variable 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.

In Python it would look like this:
== code© | 
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 puzzle asks for the minimum value this code can print. 

Categorii: