【问题标题】:Python: Modifying external variables from within a threadPython:从线程内修改外部变量
【发布时间】:2023-03-27 00:21:01
【问题描述】:

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

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

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

【问题讨论】:

  • 如果您提供代码(最好简化为有问题的部分),会更容易回答您的问题。

标签: python multithreading python-2.7 multiprocessing


【解决方案1】:

根据我对您问题的理解。在猜到你真正想要做什么之后,我创建了一个代码 sn-p。

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

下面的代码 sn-p 在名为 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

这是你要求的吗?

【讨论】:

    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-23
      • 1970-01-01
      • 1970-01-01
      • 2022-11-10
      • 2016-05-23
      • 1970-01-01
      • 2023-02-04
      • 1970-01-01
      相关资源
      最近更新 更多