如何在2个线程之间共享变量 [英] How to share a variable between 2 threads

查看:1077
本文介绍了如何在2个线程之间共享变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Windows上使用Python 2.7.3.

如何在线程之间共享变量num,以便在对num求平方后将其打印出来?

How can I share a variable num between threads, such that, after num is squared, it is printed?

我意识到我需要了解线程是如何工作的,但是文档并没有太多,在这里我也没有找到任何东西..
那么,有人可以解释一下线程如何工作以及如何在2个线程之间共享变量吗?

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?

我的代码(继续打印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()

推荐答案

此问题的一般答案是队列:

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()

打印

=== pu@pumbair:~/StackOverflow:507 > ./tst.py
setup
4 16 256 65536 4294967296

请注意,在此(和您的)代码中,num在func1和func2中都是局部变量,并且它们彼此之间没有任何关系,只是它们接收全局变量num的初始值.因此在这里 not 不共享num.而是,一个线程将其num的值放入队列中,而另一个线程将此值绑定到同名的本地(因此是不同的)变量.但是,当然可以使用任何名称.

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 not shared 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.

这篇关于如何在2个线程之间共享变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆