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

Broken counter

Cosmin
Cosmin Negruseri
23 august 2012

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

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.

Categorii: