taze totero taze totero - 1 year ago 76
Python Question

Python34 multithreading and passing a variable

So I've never been really good with multithreading and today I'm bumping into a problem I've been trying to dodge for quite some time.

I want to pass a variable to a function that I execute in multiple threads but I have no clue how to do that in a functional manner.

Here is what I made :

# This is the thread starter
a = 0
while a < threads :
a +=1
print("[" + str(a) + "/" + str(threads)+ "] Thread started")
thread = myThread(payload=payload) # payload is the variable I'd like to pass

And this is the class :

class myThread (threading.Thread):
def __init__(self):
def run (self, payload) :

And this is the error I'm getting :

TypeError: __init__() got an unexpected keyword argument 'payload'

I'd be glad if someone couldn't enlighten me on what I'm doing wrong. Thanks in advance guys!


You should read more about the Classes in python.

You forgot to define the payload parameter in the constructor of your Thread implementation. It's just simple as this:

class myThread (threading.Thread):
    def __init__(self, payload):  # you have to define the constructor parameter here
        self.payload = payload
    def run (self):

And if you do not need some extra stuff in your own Thread implementation you could simply do this:

a = 0
while a < threads:
    a +=1
    print("[{0!s}/{1!s}] Thread started".format(a, threads))
    thread = Thread(target=Checker, args=(payload,))