Benno Benno - 1 year ago 77
Python Question

Is a python dict's len() atomic with respect to the GIL?

I'm asking about CPython, python2.7. Say I have a

, and a few threads that will insert values from time to time by calling

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

Is it safe to get the size of the dict from a separate thread without grabbing the lock, relying just on the GIL?

def count():
return len(d)

Assuming that I don't care about getting precisely the correct value, just any value that was correct at some point during

Answer Source

I wouldn't recommend it, but yeah, the GIL will protect that. There's no opportunity for the GIL to be released during the len call.

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