【发布时间】:2016-08-25 09:46:39
【问题描述】:
THINGS 变量中存储了 101 个东西。
该代码声明了 101 个线程并立即同时执行所有线程。
我想知道我们是否可以将活动线程数限制为 12 个。
起初只有 12 个线程应该选择它们的 12 件事情来处理。其余线程应该等待前 12 个线程完成它们的工作。当前 12 个线程全部完成后,接下来的 12 个线程将开始处理接下来的 12 个事情。等等。
这可能吗?
import Queue
import threading, time
class MyThread(threading.Thread):
def __init__(self, theQueue=None):
threading.Thread.__init__(self)
self.theQueue=theQueue
def run(self):
thing=self.theQueue.get()
self.process(thing)
self.theQueue.task_done()
def process(self, thing):
time.sleep(1)
print 'processing %s'%thing.name
queue=Queue.Queue()
THINGS = ['Thing%02d'%i for i in range(101)]
THREADS=[]
for thing in THINGS:
thread=MyThread(theQueue=queue)
thread.name = thing
THREADS.append(thread)
thread.start()
for thread in THREADS:
queue.put(thread)
【问题讨论】:
-
看起来像一个游泳池.. docs.python.org/2/library/…
-
我想知道我们是否可以将活动线程的数量限制在 12 英尺以内。制作12个线程。不要再做。不要让它们中的任何一个终止。
-
由于 Python 使用Global Interpreter Lock 的事实,多线程对并行计算没有意义——您需要为此使用多处理(正如 Olegp 所建议的那样)。 Python 中的线程实际上只对并发应用程序有用,尤其是在多个线程可能同时阻塞的情况下。示例可能是 GUI 应用程序或多个 I/O 请求。 (有几个没有 GIL 的实现,但看起来您并没有使用其中之一。)
标签: python multithreading