I'm asking about CPython, python2.7. Say I have a dict
, and a few threads that will insert values from time to time by calling add()
:
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 count()
.
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.