is this thread safe?

Dave Brueck dave at pythonapocrypha.com
Wed Aug 25 10:06:44 EDT 2004


Joe Wong wrote:
> I have a variable that need to be incremented by 1 as follow:
>  
> v += 1
>  
> Is this threadsafe? Do I need to put a lock around this?

No[1], yes[2].

-Dave

[1] A context switch could happen between adding and saving the value:

>>> import dis
>>> def inc():
...   global v
...   v += 1
...
>>> dis.dis(inc)
  3           0 LOAD_GLOBAL              0 (v)
              3 LOAD_CONST               1 (1)
              6 INPLACE_ADD
              7 STORE_GLOBAL             0 (v)
             10 LOAD_CONST               0 (None)
             13 RETURN_VALUE

[2] Without locking, you get incorrect results:

import threading, time

ADD_COUNT = 1000000
THREAD_COUNT = 3
v = 0

def Worker():
    global v
    for i in xrange(ADD_COUNT):
        v += 1

threads = []
for i in range(THREAD_COUNT):
    t = threading.Thread(target=Worker)
    threads.append(t)
    t.start()

for thread in threads:
    thread.join()

assert v == ADD_COUNT * THREAD_COUNT, v




More information about the Python-list mailing list