nubela nubela - 1 year ago 116
Python Question

Is the += operator thread-safe in Python?

I want to create a non-thread-safe chunk of code for experimentation, and those are the functions that 2 threads are going to call.

c = 0

def increment():
c += 1

def decrement():
c -= 1

Is this code thread safe?

If not, may I understand why it is not thread safe, and what kind of statements usually lead to non-thread-safe operations.

If it is thread-safe, how can I make it explicitly non-thread-safe?

Answer Source

Single opcodes are thread-safe because of the GIL but nothing else:

import time
class something(object):
    def __init__(self,c):
    def inc(self):
        new = self.c+1 
        # if the thread is interrupted by another inc() call its result is wrong
        time.sleep(0.001) # sleep makes the os continue another thread
        self.c = new

x = something(0)
import threading

for _ in range(10000):

print x.c # ~900 here, instead of 10000

Every resource shared by multiple threads must have a lock.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download