I'm trying to wrap two threaded functions inside an object and run a couple of instances of the object. So far I could only run the objects if I pull the threading outside the class.
import threading
class MyObject:
def __init__(self, item_id):
self.item_id = item_id
def func_one(self):
# do stuff
def func_two(self):
# do another thing
# initialize objects
obj1 = MyObject("item-01")
obj2 = MyObject("item-02")
# create threads for each object
thread1_obj1 = threading.Thread(target=obj1.func_one)
thread2_obj1 = threading.Thread(target=obj1.func_two)
thread1_obj2 = threading.Thread(target=obj2.func_one)
thread2_obj2 = threading.Thread(target=obj2.func_two)
# start and join threads
thread1_obj1.start()
thread2_obj1.start()
thread1_obj2.start()
thread2_obj2.start()
thread1_obj1.join()
thread2_obj1.join()
thread1_obj2.join()
thread2_obj2.join()
Is there a way to encapsulate the threads inside the class instead of pulling them out to run the the objects?
Define a method in the class that runs both functions, each in its own thread. Then call that method from the main thread.
import threading
class MyObject:
def __init__(self, item_id):
self.item_id = item_id
def func_one(self):
# do stuff
def func_two(self):
# do another thing
def run_threads(self):
self.thread1 = threading.Thread(target=self.func_one)
self.thread2 = threading.Thread(target=self.func_two)
self.thread1.start()
self.thread2.start()
def join_threads(self):
self.thread1.join()
self.thread2.join()
obj1 = MyObject("item-01")
obj2 = MyObject("item-02")
obj1.run_threads()
obj2.run_threads()
obj1.join_threads()
obj2.join_threads()