简体   繁体   中英

Threading is working perfectly on python2.7 but not on python3.4

import threading
class MyThread(threading.Thread):
    def __init__(self, target, *args):
        self._des = target
        self._args = args
        threading.Thread.__init__(self,)
        self._stopper = threading.Event()    

    def run(self):
        self._des(*self._args)

    def stop(self):
        self._stopper.set()

    def stopped(self):
        return self._stopper.isSet()
def add(a,b):
    print(a+b)
if __name__ == "__main__":
    f1 = MyThread(add,1,2)
    f1.start()
    f1.join()

The above code is working perfectly on python2.7 but when i tried it with 3.4 it shows the following error

TypeError: add() missing 2 required positional arguments: 'a' and 'b'

Is there anyone who can help me to solve this.? Thanks in advance.

While assigning self.args = args , you get value as a tuple so you should be first taking/parsing it to tuple then pass it into your add function. So all you have to do is make a tuple out of your args .

Below is the modified code with marked line changed.

import threading
class MyThread(threading.Thread):
    def __init__(self, target, *args):
        self._des = target
        self.args = tuple(args)  // making it to tuple
        threading.Thread.__init__(self,)
        self._stopper = threading.Event()    

    def run(self):
        self._des(*self.args)

    def stop(self):
        self._stopper.set()

    def stopped(self):
        return self._stopper.isSet()
def add(a,b):
    print(a+b)
if __name__ == "__main__":
    f1 = MyThread(add, 1, 2)
    f1.start()
    f1.join()

Hope this helps.

to keep it simple, this one works

def __init__(self, target, a,b):
    self._des = target
    self._a=a
    self._b=b  
    threading.Thread.__init__(self)
    self._stopper = threading.Event()    

def run(self):
    self._des(self._a,self._b)

going by your way, you need to run the initialization first, because thats wiping out all values, like below

def __init__(self, target, *args):
    threading.Thread.__init__(self)
    self._des = target  
    self._args = tuple(args)        
    self._stopper = threading.Event()    

def run(self):
    self._des(self._args[0],self._args[1])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM