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

Python multithreading broken

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.

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 :

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()
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