You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python的while循环中实现两个函数并行运行?

Python中在while循环里实现函数并行的方案

你的原有代码是串行执行逻辑:func1执行完成(包括2秒休眠)后才会启动func2,要实现两者并行运行,推荐使用多线程(你的场景属于IO密集型,线程开销远低于进程),以下是两种可行方案:

方案1:直接使用threading模块创建线程

每次循环中启动两个独立线程,让func1和func2同时执行:

import time
import threading


def func1():
    print('1')
    time.sleep(2)


def func2():
    print('2')


if __name__ == '__main__':
    while True:
        # 为两个函数创建线程
        thread1 = threading.Thread(target=func1)
        thread2 = threading.Thread(target=func2)
        
        # 启动线程
        thread1.start()
        thread2.start()
        
        # 可选:等待两个线程都执行完毕,再进入下一次循环
        # 如果不需要等待,可删除下面两行,但会快速创建大量线程,需谨慎
        thread1.join()
        thread2.join()

执行后你会看到2立刻打印出来,无需等待func1的2秒休眠结束。

方案2:使用线程池复用线程(更高效)

如果循环次数较多,频繁创建销毁线程会有额外开销,用concurrent.futures.ThreadPoolExecutor创建线程池复用线程:

import time
from concurrent.futures import ThreadPoolExecutor


def func1():
    print('1')
    time.sleep(2)


def func2():
    print('2')


if __name__ == '__main__':
    # 创建最多容纳2个线程的线程池
    with ThreadPoolExecutor(max_workers=2) as executor:
        while True:
            # 提交两个函数到线程池执行
            future1 = executor.submit(func1)
            future2 = executor.submit(func2)
            
            # 可选:等待任务完成再进入下一次循环
            future1.result()
            future2.result()

内容的提问来源于stack exchange,提问作者slime3000fly

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 16:16:03