在一个函数中:
a += 1
编译器将解释为将值赋给a => 创建本地变量a
,这不是您想要的。它可能会出现a未初始化
的错误,因为(本地)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共享工具(锁和其他工具),或者更好的方式是通过队列来通信而不是共享数据,例如:
from threading import Thread
from queue import Queue
import time
def thread1(threadname, q):
while True:
a = q.get()
if a is None: return
print a
def thread2(threadname, q):
a = 0
for _ in xrange(10):
a += 1
q.put(a)
time.sleep(1)
q.put(None)
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()
lock = threading.Lock()
,并在thread2
中添加with lock:
来保护a+=1
吗? - alwaysday1