I'd like to use threading to run multiple methods at the same time. However, when I run the following code only testFunc1 executes. The string "test2" is never printed even once and I'm not sure why. I'd like both testFunc1 and testFunc2 to be executing at the same time. I'm very new to threading and Python in general, so any advice to regarding threading is welcome along with a solution to my problem. Here is the code:
import time, threading
class testClass:
def __init__(self):
self.count = 0
def testFunc1(self):
while True:
print(self.count)
self.count = self.count + 1
time.sleep(1)
def testFunc2(self):
while True:
print("test2")
time.sleep(1)
def run(self):
threading.Thread(target=self.testFunc1(), args=(self,)).start()
threading.Thread(target=self.testFunc2(), args=(self,)).start()
test = testClass()
test.run()
When you pass a method by self.method
/cls_object.method
then self
is passed automatically, You only need to pass self
manually in case you pass the function by testClass.testFunc2
(in your case method
is testFunc2
), so args=(self,)
is redundant.
Furthermore, you don't need to add ()
when you pass the function because you don't want to call that function but just pass its reference, hence you can fix your code to:
threading.Thread(target=self.testFunc1).start()
threading.Thread(target=self.testFunc2).start()