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

2024-04-19 01:09:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个在类中运行的线程。你知道吗

但是我想修改一个变量(比如,自变量)在那个类中从线程开始。你知道吗

因为线程创建了自变量,但是我需要在线程中动态地更新它,我该怎么做呢?你知道吗


Tags: 动态线程
2条回答

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

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

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

Q. I have a thread that runs within a class. But I want to modify a variable (say, self.variable) within that class from the thread.

下面的代码段在名为myThreadClass()的类中运行一个线程。此类的__init__()中有一个名为self.myVariable的变量。在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

这是你要的吗?你知道吗

相关问题 更多 >