【问题标题】:How to limit the number of Threads如何限制线程数
【发布时间】: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


【解决方案1】:

工作解决方案发布在下面。 基本思想是我们只声明与可用 CPU 一样多的 Threads 实例。然后我们继续将“任务”(或此处的“事物”)添加到队列中。 一旦任务被添加到队列中,它就会立即被我们在上一步中声明的 Thread 实例之一拾取。

重要提示:为了使这种机制起作用,MyThread.run() 方法应该在while 循环内运行。否则 MyThread 实例将在完成第一个任务后立即终止。在队列中没有任务离开后,while 循环将自行退出。这就是故事的结局。

import Queue
import threading, time

class MyThread(threading.Thread):
    def __init__(self, theQueue=None):
        threading.Thread.__init__(self)        
        self.theQueue=theQueue

    def run(self):
        while True:
            thing=self.theQueue.get()
            self.process(thing) 
            self.theQueue.task_done()

    def process(self, thing):
        time.sleep(1)
        print 'processing %s'%thing

queue=Queue.Queue()
THINGS = ['Thing%02d'%i for i in range(101)]
AVAILABLE_CPUS=3

for OneOf in range(AVAILABLE_CPUS):
    thread=MyThread(theQueue=queue)
    thread.start() # thread started. But since there are no tasks in Queue yet it is just waiting.

for thing in THINGS:       
    queue.put(thing) # as soon as task in added here one of available Threads picks it up

【讨论】:

  • 绝妙的答案!非常有帮助。唯一对我不起作用的是,代码从未终止,所以我使用while not theQueue.empty(): 而不是while True。为了完成这项工作,我使用THIINGS 运行for 循环,然后使用AVAILABLE_CPUS 运行for 循环,否则线程将立即终止,因为myQueue 将为空。
猜你喜欢
  • 2015-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-19
  • 2017-12-10
相关资源
最近更新 更多