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

前端 未结 7 666
再見小時候
再見小時候 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 03:07

    If you want to limit the number of parallel threads, use a semaphore:

    threadLimiter = threading.BoundedSemaphore(maximumNumberOfThreads)
    
    class EncodeThread(threading.Thread):
    
        def run(self):
            threadLimiter.acquire()
            try:
                <your code here>
            finally:
                threadLimiter.release()
    

    Start all threads at once. All but maximumNumberOfThreads will wait in threadLimiter.acquire() and a waiting thread will only continue once another thread goes through threadLimiter.release().

    0 讨论(0)
提交回复
热议问题