python多线程并发数量控制

96
wolfJiao
0.3 2018.07.22 01:11* 字数 81

python多线程如果不进行并发数量控制,在启动线程数量多到一定程度后,会造成线程无法启动的错误。
控制多线程并发数量的方法有好几钟,下面介绍用queue控制多线程并发数量的方法。python3


# -*- coding: utf-8 -*-
import threading
import queue

maxThreads = 50

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

    def run(self):
        try:
            print('This is store %s\n' % 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(1500):
        q.put(s)
        t = store(s, q)
        t.start()
    q.join()
    print('over')

if __name__ == '__main__':
    main()
日记本