运行 python 中同一函数的多个独立版本

Run multiple versions of the same function independently in python

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

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

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

谢谢!

线程将是第一个尝试的事情。下面的代码应该大致适用于您的情况。它为每个任务创建一个线程。根据您的 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()