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?
thread1_obj1variable and yourthread1_obj2variables refer to different threads, but they both have "thread1" in their names. In an enterprise-grade software engineering project, a code reviewer probably would ask you to change their names. E.g.;thread1_obj1,thread2_obj2,thread3_obj1, andthread4_obj2.