Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Python ints thread-safe?

Are Python ints thread-safe? I cannot find a definitive answer for this from Google.

like image 800
lemiant Avatar asked Dec 06 '22 21:12

lemiant


1 Answers

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
like image 163
Omnifarious Avatar answered Dec 28 '22 09:12

Omnifarious