简体   繁体   中英

Python multithreading: How to run multiple async threads in a loop

Let's Imagine the code below:

import threading
from time import sleep


def short_task():
    sleep(5)
    print("short task")

def long_task():
    sleep(15)
    print("long task")

while True:
    st = threading.Thread(target=short_task())
    lt = threading.Thread(target=long_task())
    st.start()
    lt.start()
    st.join()
    lt.join()

I have two functions that each take different times to process, in my approach above the output is going to be as below:

short task
long task
short task
long task
short task
long task
short task
long task

but the desired output is:

short task
short task
short task
long task
short task
short task
short task
long task

what is the best way to achieve this? one maybe dirty way is to remove the main while loop and put a while loop in each thread.

As you assumed in the question moving while loop to inside the threads will help to get results as you intended.

Also one more thing. You are calling the function when passing the target. You just need to pass the function name alone. eg: target=short_task

Also in your main while loop since you are waiting for thread to finish hence it makes sense that the output is coming alternatively. It is a logic mistake I believe.

Try below code should work as your expectation.

I have changed wait time of the short function to 4 instead of 5. So to make sure the order you desired is maintained.

import threading
from time import sleep


def short_task():
    while True:
        sleep(4)
        print("short task")


def long_task():
    while True:
        sleep(15)
        print("long task")


st = threading.Thread(target=short_task)
lt = threading.Thread(target=long_task)
st.start()
lt.start()
st.join()
lt.join()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM