When are Python threads fast?

﹥>﹥吖頭↗ 提交于 2019-11-30 08:58:33

Threading really only makes sense if you have a lot of blocking I/O going on. If that's the case, then some threads can sleep while other threads work. If threads are CPU-bound, you're not likely to see much benefit from multithreading.

Note that the multiprocessing module, while more difficult to code for, makes use of separate processes and therefore doesn't suffer the downsides of the GIL.

Since you seem to be looking for examples, here are some off the top of my head and grabbed from searching for CPU-bound and I/O-bound examples (I can't seem to find many). I am no expert, so please feel free to correct anything I've miscategorized. It's also worth noting that advancing technology could move a problem from one category to another.

CPU Bound Tasks (use multiprocessing)

  • Numerical methods/approximations for mathematical functions (calculating digits of pi, etc.)
  • Image processing
  • Performing convolutions
  • Calculating transforms for graphics programming (possibly handled by GPU)
  • Audio/video compression/decompression

I/O Bound Tasks (threading is probably OK)

  • Sending data across a network
  • Writing to/reading from the disk
  • Asking for user input
  • Audio/video streaming

The GIL prevents python from running multiple threads.

If your code releases the GIL before jumping into a C extension, other python threads can continue while the C code runs. Like with the blocking IO, that other people have mentioned.

Ctypes does this automatically, and so does numpy. So if your code uses them a lot, it may not be significantly restricted by the GIL.

Besides the CPU bound and I/O bound tasks, there is still more use cases. For example, thread enables concurrent tasks. A lot of GUI programming fall into this category. The main loop have to be responsive to mouse events. So anytime you have a task that take a while and you don't want to freeze the UI, you do it on a separate thread. It is less about performance and more about parallelism.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!