Python启动100个线程的速度非常慢

2024-05-19 01:36:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图利用python中的线程

我需要每个线程用不同的参数调用相同的函数(使用while(True)循环)

因此,在这个示例中,我创建了81个对象(Trader),并将它们全部附加到一个列表(traders)中。 然后,我使用concurrent.futures库启动线程

“exec_strats”是一个使用while(True)循环的函数

for ma_range in range(10, 200, 10):
    for overhead in range(1, 10, 1):
        trader = Trader(id=str(ma_range)+':'+str(overhead))
        header.append(trader.id)
        args = [trader, ma_range, overhead]
        trader.add_strat(exec_strat_sec, args)
        traders.append(trader)

start = time.time()

result = concurrent.futures.ThreadPoolExecutor(max_workers=len(traders)).map(exec_strats, traders)

end = time.time()
print("Time for "+str(len(traders))+" threads to start : " + str(end - start) + " seconds")

要启动9个线程,大约需要3秒钟。要启动100个线程,大约需要5分钟

有谁能向我解释一下我的代码是否有问题,或者我不应该使用python进行那种多线程处理,为什么


编辑1

感谢您的快速回复

为了澄清这一点,我每个任务只需要一个工人,但我需要所有工人同时工作,而不是一个接一个地工作。该任务执行一个相当简单的计算,需要永远重复


Tags: 函数truefortimerange线程startexec

热门问题