I wanted to start learning about threading in python so I grabbed myself a tutorial and started reading and coding. The following code is what I came up with.
I created a function wait that is suppoesed to print out "Waiting started" and then go to sleep for 3 seconds befor printing out "Waiting ended". I created a main function, where I create and start the thread t1. After the thread t1 started I would expect "Meanwile…" to be printed out. However the thread behaves like I initialized it with .run().
Can someone explain this behavior to me and maybe give me a solution how to fix this?
import threading
from time import sleep
def wait():
print("Waiting started")
sleep(3)
print("Waiting ended")
def main():
t1 = threading.Thread(target=wait())
t1.start()
print("Meanwhile...")
if __name__ == '__main__':
main()
I tried .start() and .run() and for some reason in both cases the output is the same, even though they have a completely diffrent functionality.
>Solution :
I think your problem is that you have written:
t1 = threading.Thread(target=wait())
When you need to write:
t1 = threading.Thread(target=wait)
You need the function because the former runs wait() and inputs what it returns (nothing) to threading.Thread, while the latter inputs the function into threading.Thread, so that it can be called later.
Full code:
import threading
from time import sleep
def wait():
print("Waiting started")
sleep(3)
print("Waiting ended")
def main():
t1 = threading.Thread(target=wait)
t1.start()
print("Meanwhile...")
if __name__ == '__main__':
main()