【问题标题】:running ten thread for each ten items in my array each time每次为我的数组中的每十个项目运行十个线程
【发布时间】:2017-11-09 00:47:17
【问题描述】:

我有一个数组,例如 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 循环的第二轮,为后十个项目运行线程。

如何每次将我的 for 循环索引增加十次?

【问题讨论】:

    标签: python arrays multithreading for-loop


    【解决方案1】:

    这是有问题的设计,因为:

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

    常用的方法是使用线程池。你可以在concurrent.futures 中搜索 Python 3.2+,或者在旧版本中(也不是太旧......)multiprocessing.pool.ThreadPool

    【讨论】:

    • 谢谢@Serge,我完全糊涂了。我只是想加快我的程序,但这是我第一次想在我的程序中使用线程。我认为 concurrent.futures 对我来说有点复杂:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-20
    • 2010-10-22
    • 2016-02-06
    • 2018-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多