I would like to build a function, which checks if a subthread is already running and if not, start a subthread with any function and paramter given. As multithreading tool I use this post: Is there any way to kill a Thread in Python?
The idea so far is the following:
from ThreadEx import ThreadEx
class MyClass:
def __init__(self):
self.__Thread = ThreadEx(name='MyClass',target="")
self.GlobalVariable = "MyClass Variable"
def SubThread(self, function):
if not self.__Thread.is_alive():
print("Thread is not alive")
self.__Thread = ThreadEx(target=function(),args=(self,))
print("Thread is going to start")
self.__Thread.start()
print("Thread started")
else:
print("There is already a subthread running")
def MyFunction1(self, argument1, argument2, argument3):
self.SubThread(lambda: MyFunction1(self, argument1,argument2,argument3))
def MyFunction2(self, argument1, argument2):
self.SubThread(lambda: MyFunction2,argument1,argument2)
def MyFunction1(self, argument1, argument2, argument3):
print(self.GlobalVariable)
print("MyFunction1")
print("Argument1: " + str(argument1))
print("Argument2: " + str(argument2))
print("Argument3: " + str(argument3))
def MyFunction2(argument1, argument2):
print("MyFunction2")
print("Argument1: " + str(argument1))
print("Argument2: " + str(argument2))
unfortunately if I execute:
from Myclass import MyClass
self.MyClass = MyClass()
self.MyClass.MyFunction1("Test1","Test2","Test3")
The output is:
Thread is not alive
MyClass Variable
MyFunction1
Argument1: Test1
Argument2: Test2
Argument3: Test3
Thread is going to start
Thread started
So the function is executed before the thread starts. So my question is, how do I send MyFunction including all arguments to a subthread and being able to repeat this with any other function without write a routine each time. I was already looking for *args and **kwargs but I couldn't find the right syntax or it was the wrong way.
Thanks in advance! :)