python - 如何限制线程数

标签 python multithreading

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)

最佳答案

工作解决方案发布在下面。 基本思想是我们只声明与可用 CPU 一样多的线程实例。然后我们继续将“任务”(或此处的“事物”)添加到队列中。 一旦任务被添加到队列中,我们在上一步中声明的 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

关于python - 如何限制线程数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36951763/

相关文章:

python - python虚拟环境出错

python - Django - 确定地理坐标是否在圆内

java - 以线程安全的方式延迟初始化 Java 映射

java - 不同显示器之前发生的情况

java - 返回值的Java并发方法调用

python - 为 Kivy-ios 编译自定义模块

python - 我如何添加与其他模型相关的选择字段并传递 id 当前对象?

python - 使用 matplotlib 绘制交互式直方图?

java - Android处理程序,不在ui线程中执行post()

ios - 在模拟器上运行应用程序时,它崩溃并提示 thread 1 : breakpoint 3. 1. 我该怎么办?