How do I limit the number of active threads in python?

前端 未结 7 653
再見小時候
再見小時候 2021-01-02 02:30

Am new to python and making some headway with threading - am doing some music file conversion and want to be able to utilize the multiple cores on my machine (o

7条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-02 02:50

    I would like to add something, just as a reference for others looking to do something similar, but who might have coded things different from the OP. This question was the first one I came across when searching and the chosen answer pointed me in the right direction. Just trying to give something back.

    import threading
    import time
    maximumNumberOfThreads = 2
    threadLimiter = threading.BoundedSemaphore(maximumNumberOfThreads)
    
    def simulateThread(a,b):
        threadLimiter.acquire()
        try:
            #do some stuff
            c = a + b
            print('a + b = ',c)
            time.sleep(3)
        except NameError: # Or some other type of error
            # in case of exception, release
            print('some error')
            threadLimiter.release()
        finally:
            # if everything completes without error, release
            threadLimiter.release()
            
            
    threads = []
    sample = [1,2,3,4,5,6,7,8,9]
    for i in range(len(sample)):
        thread = threading.Thread(target=(simulateThread),args=(sample[i],2))
        thread.daemon = True
        threads.append(thread)
        thread.start()
        
    for thread in threads:
        thread.join()
    

    This basically follows what you will find on this site: https://www.kite.com/python/docs/threading.BoundedSemaphore

提交回复
热议问题