在函数中:
a += 1
编译器会将其解释为assign to a => Create local variable a,这不是您想要的。它可能会失败并出现a not initialized 错误,因为(本地)a 确实没有被初始化:
>>> a = 1
>>> def f():
... a += 1
...
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in f
UnboundLocalError: local variable 'a' referenced before assignment
使用global 关键字(非常不受欢迎,并且有充分的理由)你可能会得到你想要的,就像这样:
>>> def f():
... global a
... a += 1
...
>>> a
1
>>> f()
>>> a
2
然而,一般来说,您应该避免使用会很快变得失控的全局变量。对于多线程程序尤其如此,因为您没有任何同步机制让您的thread1 知道a 何时被修改。简而言之:线程是复杂的,当两个(或多个)线程处理相同的值时,您不能期望对事件发生的顺序有一个直观的理解。语言、编译器、操作系统、处理器……都可以发挥作用,并出于速度、实用性或任何其他原因决定修改操作顺序。
这种事情的正确方法是使用Python共享工具(locks
和朋友),或者更好的是,通过Queue 而不是共享数据来交流数据,例如像这样:
from threading import Thread
from queue import Queue
import time
def thread1(threadname, q):
#read variable "a" modify by thread 2
while True:
a = q.get()
if a is None: return # Poison pill
print a
def thread2(threadname, q):
a = 0
for _ in xrange(10):
a += 1
q.put(a)
time.sleep(1)
q.put(None) # Poison pill
queue = Queue()
thread1 = Thread( target=thread1, args=("Thread-1", queue) )
thread2 = Thread( target=thread2, args=("Thread-2", queue) )
thread1.start()
thread2.start()
thread1.join()
thread2.join()