Python Forum

Full Version: Threading : class instance to be executed by a thread
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I want to create two threads and assign two class instances (object) to these threads.Then based on some condition, I will call the methods of those class (object methods) later. When I call class methods, will that method be executed in the thread which I created earlier?.
In Java it is done using Runnable interface. https://docs.oracle.com/javase/7/docs/ap...nable.html

import threading
from threading import Thread

class example(object):
test = On
def __init__(self, instance1, instance2):
    Thread(target =  instance1).start() # assign to first thread instnace1, the class instance
    Thread(target = instance2).start()  # assign to second thread instnace2, the class instance
    
def test(self):
    if test=='On':
Thread(target =  instance1).start() # assign to first thread instnace1, the class instance
    Thread(target = instance2).start()  # assign to second thread instnace2, the class instance

sorry i was not able to edit the post correctly. here is the sample code

1. create two threads and assign class instances
2. On callback function call the instance methods. The instance method should run in the threads created earlier.

Is it possible to run instance methods in two threads parallely on callback function?

import threading
from threading import Thread

class example(object):
test = On
def __init__(self, instance1, instance2):
    slef.instance1 = instance1
    slef.instance2 = instance2
    Thread(target = self.instance1).start() # assign to first thread instnace1, the class instance
    Thread(target = self.instance2).start() # assign to second thread instnace2, the class instance

#callback function to be called 
def callback(self):
    if example.test=='On':
       self.instance1.method1()  # call instance1 method on thread1
       self.instance2.method2()    # call instance2 method on thread2