Search code examples
pythonmultithreadingconcurrencypython-multithreading

Threading in python is not running concurrently


from time import sleep
import threading


def sleep_and_print(duration, name):
    sleep(duration)
    print(name)

t1 = threading.Thread(target=sleep_and_print(2, "three second sleep"))
t2 = threading.Thread(target=sleep_and_print(1, "one second sleep"))

t1.start()
t2.start()

t1.join()
t2.join()

https://www.online-python.com/DcL2tujayw

For the above code, my expectation is that the threads will be started async, and "one second sleep" will be printed before "three second sleep". However that is not the order this happens, they appear to be running synchronously.

From the docs I've read I believe this should work, but I am new to python. I tried using ThreadPoolExecute but could not make that work either. Thanks in advance


Solution

  • You are not executing the function in the threads, you are doing it in the threading.Thread declaration. target should be the function name and the parameters should be sent as args

    t1 = threading.Thread(target=sleep_and_print, args=(3, "three second sleep"))
    t2 = threading.Thread(target=sleep_and_print, args=(1, "one second sleep"))
    

    Test

    for _ in range(10):
        t1 = threading.Thread(target=sleep_and_print, args=(1, 'thread 1'))
        t2 = threading.Thread(target=sleep_and_print, args=(1, 'thread 2'))
        t1.start()
        t2.start()
        t1.join()
        t2.join()
    

    Output

    thread 1
    thread 2
    thread 1
    thread 2
    thread 2
    thread 1
    thread 2
    thread 1
    thread 1
    thread 2
    thread 2
    thread 1
    thread 2
    thread 1
    thread 2
    thread 1
    thread 1
    thread 2
    thread 1
    thread 2