Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing parameter to function while multithreading

I’m learning about multithreading and when I try to pass a parameter to my function in each thread it will process sequentially. Why is that?

import time
import threading

start = time.perf_counter()

def sleepy_duck(name):
    print(name, "duck going to sleep 1 sec")
    time.sleep(1)
    print(name, "waking up")    


t1 = threading.Thread(target=sleepy_duck("Johny"))
t2 = threading.Thread(target=sleepy_duck("Dicky"))
t3 = threading.Thread(target=sleepy_duck("Loly"))

t1.start()
t2.start()
t3.start()

t1.join()
t2.join()
t3.join()

finish = time.perf_counter()
print("The ducks slept ", finish-start, " seconds.")

Result:

Johny duck going to sleep 1 sec
Johny waking up
Dicky duck going to sleep 1 sec
Dicky waking up
Loly duck going to sleep 1 sec
Loly waking up
The ducks slept  3.0227753  seconds.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try this and note the difference:

import time
import threading

start = time.perf_counter()

def sleepy_duck(name):
    print(name, "duck going to sleep 1 sec")
    time.sleep(1)
    print(name, "waking up")    


t1 = threading.Thread(target=sleepy_duck, args=("Johnny",))
t2 = threading.Thread(target=sleepy_duck, args=("Dicky",))
t3 = threading.Thread(target=sleepy_duck, args=("Loly",))

t1.start()
t2.start()
t3.start()

t1.join()
t2.join()
t3.join()

finish = time.perf_counter()
print("The ducks slept ", finish-start, " seconds.")

The way you did it originally the target was None

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading