Are Python ints thread-safe? I cannot find a definitive answer for this from Google.
Yes, they are immutable, just like strings. The code x += 1
actually creates a brand new integer object and assigns it to x
.
In case it's not clear, things that are immutable are automatically thread safe because there is no way for two threads to try to modify the same thing at the same time. They can't be modified you see, because they're immutable.
Example from the interpreter:
>>> x = 2**123
>>> x
10633823966279326983230456482242756608
>>> id(x)
139652080199552
>>> a = id(x)
>>> x+=1
>>> id(x)
139652085519488
>>> id(x) == a
False
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With