Home > Enterprise >  Threading multiple methods within a class in Python [closed]
Threading multiple methods within a class in Python [closed]

Time:09-30

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()

CodePudding user response:

Try to make following changes inside run() method.

threading.Thread(target=self.testFunc1, args=[]).start()
threading.Thread(target=self.testFunc2, args=[]).start()

Basically while invoking a function inside a thread, you don't need to use () along with the function call.

so instead of using self.testFunc1() you need to specify self.testFunc1 in the target.

Since testFunc1 & testFunc2 not taking any arguments, args can be passed as an empty list. .

CodePudding user response:

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()
  • Related