The right way to limit maximum number of threads running at once?

后端 未结 7 1508
逝去的感伤
逝去的感伤 2020-11-28 03:44

I\'d like to create a program that runs multiple light threads, but limits itself to a constant, predefined number of concurrent running tasks, like this (but with no risk o

7条回答
  •  Happy的楠姐
    2020-11-28 04:31

    For apply limitation on thread creating, follow this example (it really works):

    import threading
    import time
    
    
    def some_process(thread_num):
        count = 0
        while count < 5:
            time.sleep(0.5)
            count += 1
            print "%s: %s" % (thread_num, time.ctime(time.time()))
            print 'number of alive threads:{}'.format(threading.active_count())
    
    
    def create_thread():
        try:
            for i in range(1, 555):  # trying to spawn 555 threads.
                thread = threading.Thread(target=some_process, args=(i,))
                thread.start()
    
                if threading.active_count() == 100:  # set maximum threads.
                    thread.join()
    
                print threading.active_count()  # number of alive threads.
    
        except Exception as e:
            print "Error: unable to start thread {}".format(e)
    
    
    if __name__ == '__main__':
        create_thread()
    

    Or:

    Another way to set a thread number checker mutex/lock such as below example:

    import threading
    import time
    
    
    def some_process(thread_num):
        count = 0
        while count < 5:
            time.sleep(0.5)
            count += 1
            # print "%s: %s" % (thread_num, time.ctime(time.time()))
            print 'number of alive threads:{}'.format(threading.active_count())
    
    
    def create_thread2(number_of_desire_thread ):
        try:
            for i in range(1, 555):
                thread = threading.Thread(target=some_process, args=(i,)).start()
    
                while number_of_desire_thread <= threading.active_count():
                    '''mutex for avoiding to additional thread creation.'''
                    pass
    
                print 'unlock'
                print threading.active_count()  # number of alive threads.
    
        except Exception as e:
            print "Error: unable to start thread {}".format(e)
    
    
    if __name__ == '__main__':
        create_thread2(100)
    

提交回复
热议问题