Python 如何在两个线程之间共享变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15461413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to share a variable between 2 threads
提问by pradyunsg
Using Python 2.7.3 on Windows.
在 Windows 上使用 Python 2.7.3。
How can I share a variable numbetween threads, such that, after numis squared, it is printed?
如何num在线程之间共享变量,以便在num平方后打印?
I realized that I need to understand how threads work, but docs don't have much, and I haven't found anything here either..
So, could someone explain how threads work and how to share variables between 2 threads?
我意识到我需要了解线程是如何工作的,但是文档没有太多,我也没有在这里找到任何东西..
那么,有人可以解释线程是如何工作的以及如何在两个线程之间共享变量吗?
My code (keeps printing 2)
我的代码(继续打印2)
import threading
def func1(num):
while num < 100000000:
num = num**2
def func2(num):
while num < 100000000:
print num,
num = 2
thread1 = threading.Thread(target=func1,args=(num,))
thread2 = threading.Thread(target=func2,args=(num,))
print 'setup'
thread1.start()
thread2.start()
采纳答案by uselpa
The general answer to this question is queues:
这个问题的一般答案是队列:
import threading, queue
def func1(num, q):
while num < 100000000:
num = num**2
q.put(num)
def func2(num, q):
while num < 100000000:
num = q.get()
print num,
num = 2
q = queue.Queue()
thread1 = threading.Thread(target=func1,args=(num,q))
thread2 = threading.Thread(target=func2,args=(num,q))
print 'setup'
thread1.start()
thread2.start()
printing
印刷
=== pu@pumbair:~/StackOverflow:507 > ./tst.py
setup
4 16 256 65536 4294967296
Notice that in this (and your) code, num is a local variable in both func1 and func2, and they bear no relationship to each other except that they receive the initial value of the global variable num. So num is notshared here. Rather, one thread puts the value of its num into the queue, and the other binds this value to a local (and thus different) variable of the same name. But of course it could use any name.
请注意,在此(和您的)代码中,num 是 func1 和 func2 中的局部变量,它们之间没有任何关系,只是它们接收全局变量 num 的初始值。所以 num不在这里共享。相反,一个线程将其 num 的值放入队列,另一个线程将此值绑定到同名的本地(因此不同)变量。但当然它可以使用任何名称。

