栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

变量交换是否保证在python中是原子的?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

变量交换是否保证在python中是原子的?

让我们来看看:

>>> x = 1>>> y = 2>>> def swap_xy():...   global x, y...   (x, y) = (y, x)... >>> dis.dis(swap_xy)  30 LOAD_GLOBAL   0 (y)   3 LOAD_GLOBAL   1 (x)   6 ROT_TWO     7 STORE_GLOBAL  1 (x)  10 STORE_GLOBAL  0 (y)  13 LOAD_ConST    0 (None)  16 RETURN_VALUE

它不会出现,他们是原子:x的和y的值可以被另一个线程之间改变

LOAD_GLOBAL
字节码,之前或之后
ROT_TWO
,和之间的
STORE_GLOBAL
字节码。

如果要原子交换两个变量,则需要一个锁或一个互斥锁。

对于那些需要经验证明的人:

>>> def swap_xy_repeatedly():...   while 1:...     swap_xy()...     if x == y:...       # If all swaps are atomic, there will never be a time when x == y....       # (of course, this depends on "if x == y" being atomic, which it isn't;...       #  but if "if x == y" isn't atomic, what hope have we for the more complex...       #  "x, y = y, x"?)...       print 'non-atomic swap detected'...       break... >>> t1 = threading.Thread(target=swap_xy_repeatedly)>>> t2 = threading.Thread(target=swap_xy_repeatedly)>>> t1.start()>>> t2.start()>>> non-atomic swap detected


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/639006.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号