Pregunta

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.

Since the thread creates a copy of self.variable, but I need to update it on the fly within the thread, how do I go about doing this?

¿Fue útil?

Solución

As per my understanding of your question. I have created a code snippet, after guessing what you really want to do.

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.

The code snippet below runs a thread in the class named as myThreadClass(). This class has a variable named as self.myVariable in its __init__(). In the run() the value of self.myVariable is incremented/modified for the demo purpose. Later the value of self.myVariable is printed from the myThreadClass() itself as well as it is later printed from the main() too.

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

The console output will be:

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

Is this what you asked for?

Otros consejos

i suggest you tho create your thread class like this

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
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top