Reputation: 4365
Are Python ints thread-safe? I cannot find a definitive answer for this from Google.
Upvotes: 8
Views: 9371
Reputation: 923
Int in Python is immutable which means it cannot be modified later, and any value change is a process of assigning a new immutable Int object to the original one.
But it never means any operation in Python syntax is thread-safe even GIL effects. For example: x+=1 is not thread-safe at all.
To ensure thread-safety in your code, you need to find if the operation on one object is thread-safe. The object itself does not guarantee thread-safety, nor GIL does.
Reference: is += in python thread safe?
Upvotes: 5
Reputation: 56128
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
Upvotes: 11
Reputation: 2358
Like the other have said, Python objects are mostly thread-safe. Although you will need to use Locks in order to protect an object in a place that require it to go through multiple changes before being usable again.
Upvotes: 4