taze totero
taze totero

Reputation: 359

Python 3.4 multi threading and passing a variable

So I've never been really good with multi threading 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
        thread.start()

And this is the class :

 class myThread (threading.Thread):
 def __init__(self):
     threading.Thread.__init__(self)
 def run (self, payload) :
     Checker(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!

Upvotes: 1

Views: 1091

Answers (2)

TryToSolveItSimple
TryToSolveItSimple

Reputation: 893

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
        threading.Thread.__init__(self)
        self.payload = payload
    def run (self):
        Checker(self.payload)

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,))
    thread.start()

Upvotes: 1

Alex Hall
Alex Hall

Reputation: 36013

TryToSolveItSimple's answer is correct, but it's worth noting that this is a very common pattern for which there is already a primitive:

from multiprocessing.pool import ThreadPool
from contextlib import closing

def Checker(a):
    print(a)

threads = 4
with closing(ThreadPool(threads)) as pool:
    pool.map(Checker, range(threads))

This will print the numbers 0 to 3 in parallel.

The with closing part isn't strictly necessary for this to work, but like a file, a pool should be closed when you're done with it.

Upvotes: 2

Related Questions