简体   繁体   English

python2.7线程池比逐个启动线程快很多

[英]python2.7 threading pool is much faster than starting the thread one by one

i did some testing on the thread pool and starting the thread one by one.我对线程池进行了一些测试并一一启动线程。 It is much faster when using the thread pool.使用线程池时速度要快得多。 i can figure out why?我能弄清楚为什么?

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

[Running] python -u "c:\Users\eguozqu\git\test\thread_test.py" ['This is string no. [运行] python -u "c:\Users\eguozqu\git\test\thread_test.py" ['这是字符串编号。 1', 'This is string no. 1', '这是字符串编号。 2', 'This is string no. 2', '这是字符串编号。 3', 'This is string no. 3', '这是字符串编号。 4', 'This is string no. 4', '这是字符串编号。 5', 'This is string no. 5', '这是字符串编号。 6', 'This is string no. 6', '这是字符串编号。 7', 'This is string no. 7', '这是字符串编号。 8', 'This is string no. 8', '这是字符串编号。 9'] 9']

[Done] exited with code=0 in 45.353 seconds [完成] 在 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()

[Running] python -u "c:\Users\eguozqu\git\test\process_test.py" [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] [运行中] python -u "c:\Users\eguozqu\git\test\process_test.py" [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

[Done] exited with code=0 in 5.393 seconds [完成] 在 5.393 秒内以 code=0 退出

When you do threading.Thread(stringFunction(str(i), my_queue)) you are calling stringFunction and passing the result to threading.Thread 's initialiser instead of passing the function itself.当您执行threading.Thread(stringFunction(str(i), my_queue))时,您正在调用stringFunction并将结果传递给threading.Thread的初始化程序,而不是传递 function 本身。

This means that each time you create a thread you first wait for that function call to complete.这意味着每次创建线程时,您首先等待 function 调用完成。

What you probably want is threading.Thread(target=stringFunction, args=(str(i), my_queue)) .您可能想要的是threading.Thread(target=stringFunction, args=(str(i), my_queue))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM