J
J
Junior932021-06-18 18:56:53
Python
Junior93, 2021-06-18 18:56:53

Are there any differences between asynchronous and multi-threaded code in the context of Python?

Tell me, plz, what are the differences between executing code in python with its gil in asynchronous and multi-threaded code.
Are there cases when it is better to write multi-threaded code in python than asynchronous?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey Gornostaev, 2021-06-18
@Junior93

If you need to make blocking calls concurrently, you simply cannot do without threads. Asynchrony only works when the entire call chain from start to finish is asynchronous.

D
Daniil Shevkunov, 2021-06-18
@danila763

Neighing over the comment (no offense), although in principle the first one is right, in general - as we remember, modern processors have several cores, plus each core can perform several tasks at once, and multithreading is when several parts of the code are executed independently, for example, two the program works for you, you can press buttons, it will react, but in a separate thread it will have a cycle that will count something.
Asynchrony also allows you to perform two cycles, but its essence is that the pieces of the cycles are executed in turn, in one thread - the first cycle is half, then the second is half, again the first - from the middle to the end, again the second, also from the middle to the end , and so on.
But if you use sleep() in Asynchrony, the execution of the entire program will be interrupted, and only the thread where sleep() is called will be interrupted in multithreading
. Thread 1 needs a result from thread 2, which, in turn, has not yet been received, and an error appears. This should be decided in your own way
. Actually, what to use depends on the task, but asynchrony is still simpler despite some disadvantages, and takes less computer resources, plus some well-known libraries, such as aiogram, use asynchrony, so it’s worth dealing with it (although multithreading is useful too)

O
OCTAGRAM, 2021-06-18
@OCTAGRAM

With true multithreading, non-Python code, such as long-running math library calls, can be executed completely in parallel. Or database adapters often don't have an asynchronous version. On the other hand, real threads are quite expensive in terms of resources such as stack and kernel objects, which limits their number to around 1000, but generally no more than 50 is better without the need

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question