在我的数组中每十个项目运行十个线程

2024-03-29 07:01:58 发布

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

我有一个数组,例如100个项目,我想为我的数组的每10个项目运行10个线程。你知道吗

我的问题是,我不知道如何使用for循环为第一个10项、第二个10项等运行10个线程

我需要的是:

for item in myarray:
    thread.start_new_thread(first_item)
    thread.start_new_thread(second_item)
    thread.start_new_thread(third_item)
    thread.start_new_thread(fourth_item)
    thread.start_new_thread(fifth_item)
    thread.start_new_thread(sixth_item)
    thread.start_new_thread(seventh_item)
    thread.start_new_thread(eight_item)
    thread.start_new_thread(ninth_item)
    thread.start_new_thread(tenth_item)

对于for循环的第二轮,运行第二个10项的线程。你知道吗

如何每次将for循环的索引增加10倍?你知道吗


Tags: 项目innewfor数组item线程thread
1条回答
网友
1楼 · 发布于 2024-03-29 07:01:58

这是值得怀疑的设计,因为:

  • 为每个项目启动一个新线程,而不是重复使用它们(创建线程的成本很高)
  • 您没有解释如何同步线程以将其数量限制为10个(您真的要等待前一批10个线程完成后再开始10个吗?)你知道吗

常见的方法是使用线程池。您可以在concurrent.futures中搜索Python3.2+,或者在较旧的版本(也不是太旧…multiprocessing.pool.ThreadPool)中搜索。你知道吗

相关问题 更多 >