简体   繁体   English

Python 多线程:如何在循环中运行多个异步线程

[英]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:我有两个函数,每个函数都需要不同的时间来处理,在我上面的方法中,output 将如下所示:

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

but the desired output is:但所需的 output 是:

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.一种可能是肮脏的方法是删除主while循环并在每个线程中放置一个while循环。

As you assumed in the question moving while loop to inside the threads will help to get results as you intended.正如您在问题中假设的那样,将 while 循环移动到线程内部将有助于获得您想要的结果。

Also one more thing.还有一件事。 You are calling the function when passing the target.通过目标时,您正在调用 function。 You just need to pass the function name alone.您只需要单独传递 function 名称即可。 eg: target=short_task例如: 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.同样在您的主 while 循环中,因为您正在等待线程完成,因此 output 交替出现是有道理的。 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.我已将短 function 的等待时间更改为 4 而不是 5。因此,请确保保持所需的顺序。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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