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

前端 未结 7 652
再見小時候
再見小時候 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:58

    It looks to me that what you want is a pool of some sort, and in that pool you would like the have n threads where n == the number of processors on your system. You would then have another thread whose only job was to feed jobs into a queue which the worker threads could pick up and process as they became free (so for a dual code machine, you'd have three threads but the main thread would be doing very little).

    As you are new to Python though I'll assume you don't know about the GIL and it's side-effects with regard to threading. If you read the article I linked you will soon understand why traditional multithreading solutions are not always the best in the Python world. Instead you should consider using the multiprocessing module (new in Python 2.6, in 2.5 you can use this backport) to achieve the same effect. It side-steps the issue of the GIL by using multiple processes as if they were threads within the same application. There are some restrictions about how you share data (you are working in different memory spaces) but actually this is no bad thing: they just encourage good practice such as minimising the contact points between threads (or processes in this case).

    In your case you are probably intersted in using a pool as specified here.

提交回复
热议问题