【问题标题】:How to limit the number of Thread objects created?如何限制创建的 Thread 对象的数量?
【发布时间】:2017-05-19 13:43:28
【问题描述】:

我想在下面的代码中限制同时运行的class_f 对象的数量。即限制同时工作的线程数。我怎样才能做到这一点 ?

#!/usr/bin/env python

import random
import time
from threading import Thread

list_num = [1,2,3,4,5,6,7,8,9,10]

class class_f(Thread):

    def  __init__(self,x):
        Thread.__init__(self)
        self.x = x

    def run(self):

        time.sleep(random.randint(0,1))
        res = self.x * self.x
        print str(res)+"\n"


def main():
    for num in list_num:
        c=class_f(num)
        c.start()

if __name__ == "__main__":
    main()

【问题讨论】:

    标签: python multithreading


    【解决方案1】:

    您可以在 multiprocessing.pool 中使用大部分未记录的 ThreadPool 类,因为与您自己编写(听起来像是您需要的)相比,它使您想做的事情变得容易。

    以下是如何将其应用于您问题中的代码(我还对其进行了修改以更符合PEP 8 - Style Guide for Python Code 建议):

    from multiprocessing.pool import ThreadPool
    import random
    from threading import Lock, Thread
    import time
    
    MAX_THREADS = 5
    threads = []
    list_num = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    print_lock = Lock()  # Prevents overlapped printing from threads.
    
    class ClassF(Thread):
        def  __init__(self, x):
            Thread.__init__(self)
            self.x = x
    
        def run(self):
            time.sleep(random.randint(0, 1))
            res = self.x * self.x
            with print_lock:
                print(str(res) + '\n')
    
    
    def main():
        pool = ThreadPool(processes=MAX_THREADS)
        for num in list_num:
            pool.apply_async(ClassF(num).start)
    
        pool.close()  # No more tasks will be submitted.
        pool.join()  # Wait for all threads to exit.
    
    if __name__ == "__main__":
        main()
    

    【讨论】:

      【解决方案2】:

      我建议使用有界信号量。 你可以这样实现它:

      maxThreads = 10
      semaphore = threading.BoundedSemaphore(maxThreads)
      

      然后在你的__init__ 调用sempahore.acquire() 在线程开始工作之前。当线程完成时调用sempahore.release()。 Acquire 递减存储在信号量中的数字。如果您尝试获取一个值为 0 的信号量,它将等到该信号量再次被释放。请查看 Fredrik Lundh 的 Thread Synchronization Mechanisms in Python,以更深入地了解使用 semaphores

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-12-16
        • 2012-06-19
        • 2014-05-17
        • 2019-11-01
        • 1970-01-01
        • 2020-01-07
        • 1970-01-01
        相关资源
        最近更新 更多