【问题标题】:Run multiple versions of the same function independently in python在python中独立运行同一函数的多个版本
【发布时间】:2021-08-12 09:28:22
【问题描述】:

我目前有一个 for 循环,它在每次迭代时创建一个 pandas 数据帧并启动一个函数,该数据帧是函数的参数:

for ii in hold_:
        
 temp_df = runners_df[runners_df['market_id'] == ii]
 from odds import odds
 odds(temp_df ) 

有没有一种方法可以独立但同时运行循环中调用的函数的所有版本。我想在函数中添加可变时间延迟,因此循环中的某些版本的函数可能不会在 5 小时内完成,而有些版本几乎会立即完成。我可以为此使用线程吗?

谢谢!

【问题讨论】:

标签: python for-loop python-multithreading


【解决方案1】:

线程是首先要尝试的。下面的代码应该大致适用于您的情况。它为每个任务创建一个线程。根据您的 odds 所做的事情,您的代码可以使用 muliprocessing 进一步增强,但会增加复杂性。

from odds import odds
from threading import Thread


threads: list[Thread] = []
for ii in hold_:
    temp_df = runners_df[runners_df['market_id'] == ii]
    th = Thread(target=odds, args= (temp_df,), name=f"Thread #{ii}")
    threads.append(th)
    th.start()

for th in threads:
    th.join()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-27
    • 2022-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多