Python int 是线程安全的吗?
Python int 是线程安全的吗?我无法从谷歌上找到明确的答案。
Are Python ints thread-safe? I cannot find a definitive answer for this from Google.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,它们是不可变的,就像字符串一样。代码
x += 1
实际上创建了一个全新的整数对象并将其分配给x
。如果不清楚的话,不可变的东西自动是线程安全的,因为两个线程无法尝试同时修改相同的东西。您看,它们无法修改,因为它们是不可变的。
解释器的示例:
Yes, they are immutable, just like strings. The code
x += 1
actually creates a brand new integer object and assigns it tox
.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:
Python 中的 Int 是不可变的,这意味着它以后无法修改,任何值更改都是将一个新的不可变 Int 对象分配给原始对象的过程。
但这并不意味着Python语法中的任何操作都是线程安全的,即使是GIL效果也是如此。
例如:x+=1 根本不是线程安全的。
为了确保代码中的线程安全,您需要确定对一个对象的操作是否是线程安全的。
对象本身不保证线程安全,GIL 也不保证。
参考:
Python 中的 += 线程安全吗?
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?
正如其他人所说,Python 对象大多是线程安全的。尽管您需要使用锁来保护某个地方的对象,要求它在再次可用之前经历多次更改。
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.