Home > Blockchain >  Passing parameter to function while multithreading
Passing parameter to function while multithreading

Time:08-06

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.

CodePudding user response:

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

CodePudding user response:

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",))
  • Related