0

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.

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

You're not actually multithreading. You're invoking the sleepy_duck method when setting up your threads.

the correct way is to:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.