Python:修改线程内的外部变量

时间:2014-04-18 10:57:56

标签: python multithreading python-2.7 multiprocessing

我有一个在类中运行的线程。

但是我想从线程中修改该类中的变量(比如self.variable)。

由于线程创建了self.variable的副本,但是我需要在线程内动态更新它,我该怎么做呢?

2 个答案:

答案 0 :(得分:1)

根据我对你的问题的理解。在猜出你真正想要做什么之后,我创建了一个代码片段。

  

即可。我有一个在类中运行的线程。但我想修改一个   来自线程的该类中的变量(例如,self.variable)。

下面的代码片段在名为myThreadClass()的类中运行一个线程。该类在self.myVariable中有一个名为__init__()的变量。在run()中,self.myVariable的值会增加/修改以用于演示目的。之后,self.myVariable的值将从myThreadClass()本身打印出来,以后也会从main()打印出来。

from threading import Thread
import time

class myThreadClass(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.myVariable = 0

        print ('Value of myVariable is: %d')%self.myVariable#Initial value
        self.daemon = False
        print 'Starting Child thread.\n'
        self.start()
    def run(self):
        k = 1
        for i in range(0,5):
            self.myVariable = self.myVariable+k #Increment the value and assign
            print ('Value of self.myVariable now is: %d')%self.myVariable#Print current value
            k += 1

        print 'The final value of self.myVariable is: %d'%self.myVariable
        print 'Child thread finished its job'

if __name__ == "__main__":
    obj = myThreadClass()
    time.sleep(2)
    print 'This is the main thread. The value of self.myVariable is: %d'%obj.myVariable

控制台输出将是:

Value of myVariable is: 0
Starting Child thread.

Value of myVariable now is: 1
Value of myVariable now is: 3
Value of myVariable now is: 6
Value of myVariable now is: 10
Value of myVariable now is: 15
The final value of self.myVariable is: 15
Child thread finshed its job
This is the main thread. The value of myVariable is: 15

这是你要的吗?

答案 1 :(得分:0)

我建议你像这样创建你的线程类

class ThClass( threading.Thread ):

   # parent is a object of Main, below
    def __init__( self,parent):
       super(ThClass,self).__init__()
       parent.yourvar=x
    ......do stuff


class Main():

   def __init__(self):
     super(Main,self).__init__()
     self.myth=ThClass(self)
     self.myth.start()
     ......do stuff