Is python dict len ​​() atom relative to GIL?

I am asking about CPython, python2.7. Let's say I have a dictfew threads that insert values ​​from time to time, calling add():

d = {}
dlock = threading.Lock()
def add(key, value):
    with dlock:
        d[key] = value

Is it safe to get dict size from a separate thread without locking capture, relying only on GIL?

def count():
    return len(d)

Assuming I don't care about the exact right value, just any value that was right at some point in time count().

+4
source share
1 answer

I would not recommend it, but yes, GIL will protect it. There is lenno way to issue a GIL when called .

+1
source

Source: https://habr.com/ru/post/1652227/


All Articles