开发者

Python threading, queuing, asyncing... What does it all mean?

开发者 https://www.devze.com 2023-01-24 17:13 出处:网络
I\'ve been experimenting with threading recently in Python and was curious when to use what. For开发者_如何学运维 example, when should I use multithreading over multiprocessing? What would be a scena

I've been experimenting with threading recently in Python and was curious when to use what.

For开发者_如何学运维 example, when should I use multithreading over multiprocessing? What would be a scenario when I should be using asynchronous IO rather than threading?

I mostly understand what each does (I think) but I can't see any benefits/downsides of using one over the other.

  • What should I use if I was creating a small HTTP server?
  • What should I use if I was creating a small HTTP client?

This baffles me...


What you want talk about is not specific to python only it's about multiprocessing vs threading in general i think you can find in google lot of argument from the two side the ones that prefer threading and the others that prefer multiprocessing.

But for python multi-threading is limited (if you're using CPython) by the GIL (Global Interpreter Lock), so most python programmer prefer using the multiprocessing over the threading (it's Guido recommendation)

Nevertheless, you re right the GIL is not as bad as you would initially think: you just have to undo the brainwashing you got from Windows and Java proponents who seem to consider threads as the only way to approach concurrent activities, Guido van Rossum.

you can find here some more info


Python multiprocessing makes sense when you have a machine with multiple cores and/or CPUs. The main difference between using threads and processes is that processes do not share an address space, and thus one process cannot easily access the data of another process. That is why the multiprocessing module provides managers and queues and stuff like that.

The issue with threading is Pythons Global Interpreter Lock, which seriously messes with multithreaded applications.

Asynchronous IO is useful when you have long running IO operations (read large file, wait for response from network) and do not want your application to block. Many operating systems offer built-in implementations of that.

So, for your server you would probably use multiprocessing or multithreading, and for your client async IO is more fitting.

0

精彩评论

暂无评论...
验证码 换一张
取 消