为什么一个简单的 python 生产者/消费者多线程程序不能通过增加工人的数量来加速?

问题描述

下面的代码与 http://docs 上的 python 官方队列示例几乎相同.python.org/2/library/queue.html

from Queue import Queue
from threading import Thread
from time import time
import sys

num_worker_threads = int(sys.argv[1])
source = xrange(10000)

def do_work(item):
    for i in xrange(100000):
        pass

def worker():
    while True:
        item = q.get()
        do_work(item)
        q.task_done()

q = Queue()

for item in source:
    q.put(item)

start = time()

for i in range(num_worker_threads):
    t = Thread(target=worker)
    t.daemon = True
    t.start()

q.join()

end = time()

print(end - start)

这些是在 Xeon 12 核处理器上的结果:

These are the results on a Xeon 12-core processor:

$ ./speed.py 1
12.0873839855

$ ./speed.py 2
15.9101941586

$ ./speed.py 4
27.5713479519

我预计增加工作人员的数量会减少响应时间,但实际上它正在增加.我做了一次又一次的实验,但结果没有改变.

I expected that increasing the number of workers reduce the response time but instead, it is increasing. I did the experiment again and again but the result didn't change.

我是否遗漏了一些明显的东西?还是 python 队列/线程不能正常工作?

Am I missing something obvious? or the python queue/threading doesn't work well?


解决方案

Python 在多线程方面表现相当差.由于全局锁,一次只有一个线程通常会取得进展.请参阅 http://wiki.python.org/moin/GlobalInterpreterLock

Python is rather poor at multi-threading. Due to a global lock only one thread normally makes progress at a time. See http://wiki.python.org/moin/GlobalInterpreterLock

相关文章