用Queue控制python多线程并发数量

python多线程如果不进行并发数量控制,在启动线程数量多到一定程度后,会造成线程无法启动的错误。

下面介绍用Queue控制多线程并发数量的方法(python3).

# -*- coding: utf-8 -*-
import threading
import Queue
import random
import time

maxThreads = 3

class store(threading.Thread):
    def __init__(self, store, queue):
        threading.Thread.__init__(self)
        self.queue = queue
        self.store = store

    def run(self):
        try:
            time.sleep(random.randint(1,3))
            print('This is store %s' % self.store)
        except Exception as e:
            print(e)
        finally:
            self.queue.get()
            self.queue.task_done()

def main():
    q = Queue.Queue(maxThreads)
    for s in range(15):
        q.put(s)
        t = store(s, q)
        t.start()
    q.join()
    print('over')

if __name__ == '__main__':
    main()
This is store 1
This is store 3
This is store 0
This is store 2
This is store 4
This is store 6
This is store 5
This is store 7
This is store 8
This is store 9
This is store 11
This is store 13
This is store 10
This is store 12
This is store 14
over
>>> 
技术不行 业务不行 管理不行
原文地址:https://www.cnblogs.com/onelang/p/10076190.html