rocket
rocket

Reputation: 217

Python Threading - Crash with multiple threads

I wrote a small python script using Python's threading module for multi-threading.
The target function that gets called by threading.Thread takes 2 arguments (self and another value). But I always get the following error TypeError: example() takes 2 positional arguments but 3 were given even if only 2 arguments are given.

import threading
import random
num=random.randint(1,999)

threadN=10 #number of processes
a="11" #testing value
class ExampleClass():
    def __init__(self):
        self.num=num

    def example(self,a):
        print(self.num)
        print(a)

if __name__ == '__main__':
    cl=ExampleClass()
    while threadN>0:

        threading.Thread(target=cl.example, args=(a)).start()
        threadN-=1

Any help would be appreciated!

Upvotes: 1

Views: 2895

Answers (2)

furas
furas

Reputation: 142641

args has to be list or tuple but () doesn't create tuple. You have to use comma to create tuple with single value - args=(a,)

 threading.Thread(target=cl.example, args=(t,)).start()

() is here only to separate comma which creates tuple from comma which separate arguments in function. You could do the same without ()but you would have to create tuple before thread

 arguments = a,
 threading.Thread(target=cl.example, args=arguments).start()

Upvotes: 3

rocket
rocket

Reputation: 217

Okay, just found my issue, looked again in the docs and found out following thing:

threading.Thread(target=cl.example args=[t]).start() Using [ ] for the arguments solves the problem...

Upvotes: 2

Related Questions