[英]python2.7 threading pool is much faster than starting the thread one by one
我對線程池進行了一些測試並一一啟動線程。 使用線程池時速度要快得多。 我能弄清楚為什么?
import threading
import Queue
import time
def stringFunction(value, out_queue):
my_str = "This is string no. " + value
time.sleep(5)
out_queue.put(my_str)
my_queue = Queue.Queue()
i = 1
threads = []
while i<10:
thread = threading.Thread(stringFunction(str(i), my_queue))
thread.start()
threads.append(thread)
i = i + 1
for thread in threads:
thread.join()
func_value = list(my_queue.queue)
print func_value
[運行] python -u "c:\Users\eguozqu\git\test\thread_test.py" ['這是字符串編號。 1', '這是字符串編號。 2', '這是字符串編號。 3', '這是字符串編號。 4', '這是字符串編號。 5', '這是字符串編號。 6', '這是字符串編號。 7', '這是字符串編號。 8', '這是字符串編號。 9']
[完成] 在 45.353 秒內以 code=0 退出
from multiprocessing.pool import ThreadPool as Pool
import time
class someClass(object):
def __init__(self):
pass
def f(self, x):
time.sleep(5)
return x*x
def go(self):
p = Pool(10)
sc = p.map(self, range(10))
print sc
def __call__(self, x):
return self.f(x)
sc = someClass()
sc.go()
[運行中] python -u "c:\Users\eguozqu\git\test\process_test.py" [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[完成] 在 5.393 秒內以 code=0 退出
當您執行threading.Thread(stringFunction(str(i), my_queue))
時,您正在調用stringFunction
並將結果傳遞給threading.Thread
的初始化程序,而不是傳遞 function 本身。
這意味着每次創建線程時,您首先等待 function 調用完成。
您可能想要的是threading.Thread(target=stringFunction, args=(str(i), my_queue))
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.