Chinaunix
标题:
学习Python多线程中无法修改global变量的问题
[打印本页]
作者:
rootsoso
时间:
2010-06-01 09:02
标题:
学习Python多线程中无法修改global变量的问题
最近学习Python的多线程,有一个初学例子搞得不太清除:
import thread
i = 11
def doit(ind):
global i
mutex.acquire()
temp = 1
i = temp + 1
print "i=%d" % i
mutex.release()
mutex=thread.allocate_lock()
for ind in range(10):
thread.start_new(doit,(ind,))
raw_input()
复制代码
Python版本:2.6.2
因为有thread lock,例子的原文说会输出从2,3,4 。。。。直到11. 但是我运行了以后并不是这样:
i=2
i=2
i=2
i=2
i=2
i=2
i=2
i=2
i=2
i=2
复制代码
貌似是每个thread并没有取得global i的值。
作者:
luffy.deng
时间:
2010-06-01 09:42
本帖最后由 luffy.deng 于 2010-06-01 09:44 编辑
global i
mutex.acquire()
temp = 1
i = temp + 1
print "i=%d" % i
复制代码
这跟 i=2 有什么区别?
作者:
TMBest
时间:
2010-06-01 16:56
temp = 1
i = temp + 1
这个i永远都是2了
作者:
luffy.deng
时间:
2010-06-01 17:22
本帖最后由 luffy.deng 于 2010-06-01 19:00 编辑
......
作者:
rootsoso
时间:
2010-06-01 19:40
回复
3#
TMBest
晕 我真二 ....
欢迎光临 Chinaunix (http://bbs.chinaunix.net/)
Powered by Discuz! X3.2