您可以为此使用线程池:
import threading
from multiprocessing.pool import ThreadPool
def test_thread(elem):
return elem ** 2
a = [1,2,3,4,5,6,7,8]
pool = ThreadPool(2) # 2 worker threads
results = []
for x in range(8):
print x
results.append(pool.apply_async(test_thread, args=(a[x],)))
results = [result.get() for result in results]
# You can also replace this for loop altogether using pool.map
# and get the same result:
# results = pool.map(test_thread, range(8))
print(results)
Output:
0
1
2
3
4
5
6
7
[1, 4, 9, 16, 25, 36, 49, 64]
The ThreadPool
类是大部分没有记录的部分multiprocessing模块。也可以通过以下方式访问multiprocessing.dummy.Pool。它允许您创建一个线程池来处理任意数量的工作项,同时始终将同时处理的工作项数量限制为您指定的数量。您可以使用正常的文档multiprocessing.Pool了解其 API。它是完全相同的,除了所有地方都说“进程”,你用“线程”替换它。
我不确定我是否遵循了你问题的第二部分Queue.Queue
。在 for 循环的每次迭代中,您都会将一项放入Queue
inside test_thread
,然后在 for 循环中使用它results.append(q.get())
。因此,虽然列表中永远不会有超过一项的项目Queue
一次,它被用来传输最终出现在results
列表 - 中的每一项都有一个range(8)
list.