用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
>>> 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM