簡體   English   中英

每次在數組中為每十個項目運行十個線程

[英]running ten thread for each ten items in my array each time

我有一個數組,例如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循環的索引增加十次?

這是有問題的設計,因為:

  • 您為每個項目啟動了一個新線程,而不是重復使用它們(創建線程非常昂貴)
  • 您沒有解釋如何同步線程以將它們的數量限制為十個(您真的要等待10個線程的第一束完成以啟動另外十個線程嗎?)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM