python 中变量交换保证是原子的吗?
参考以下链接: http://docs.python.org/faq/library.html#what-kinds-of-global-value-mutation-are-thread-safe
我想知道是否
(x, y) = (y, x)
可以保证 以下内容: cPython 中的原子。 (x和y都是python变量)
With reference to the following link: http://docs.python.org/faq/library.html#what-kinds-of-global-value-mutation-are-thread-safe
I wanted to know if the following:
(x, y) = (y, x)
will be guaranteed atomic in cPython. (x and y are both python variables)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
让我们看看:
它们似乎不是原子的:x 和 y 的值可以由
LOAD_GLOBAL
字节码之间、ROT_TWO
之前或之后的另一个线程更改,以及STORE_GLOBAL
字节码之间。如果你想原子地交换两个变量,你将需要一个锁或一个互斥体。
对于那些想要实证证据的人:
Let's see:
It doesn't appear that they're atomic: the values of x and y could be changed by another thread between the
LOAD_GLOBAL
bytecodes, before or after theROT_TWO
, and between theSTORE_GLOBAL
bytecodes.If you want to swap two variables atomically, you'll need a lock or a mutex.
For those desiring empirical proof:
是的,是的,会的。我经修正。。
Yes, yes it will.I stand corrected.