When to use threading and how many threads to use

后端 未结 3 1786
情话喂你
情话喂你 2021-01-15 09:06

I have a project for work. We had written a module and there as a #TODO to implement threading to improve the module. I\'m a fairly new python programmer and decided to take

3条回答
  •  温柔的废话
    2021-01-15 10:02

    Threading in python is used to run multiple threads (tasks, function calls) at the same time. Note that this does not mean that they are executed on different CPUs. Python threads will NOT make your program faster if it already uses 100 % CPU time. In that case, you probably want to look into parallel programming.

    from: https://en.wikibooks.org/wiki/Python_Programming/Threading

    This is due to the mechanism called GIL. As Daniel pointed out, threads in python are only useful when you have IO-bound code. But then again, for IO-bound code it may be better to use lighter threads running on top of some event loop (using gevent, eventlet, asyncio or similar) as then you can easily run 100s (and more) of parallel operations with very little per thread overhead.

    If what you want is to use more than 1 core of CPU to speed up execution, take a look at multiprocessing module.

提交回复
热议问题