What Is Concurrency?
asyncio
is a Python library for writing concurrent code using the async, await
syntax. In this lesson, you’ll learn what concurrency is and when to use asyncio
.
00:00
So, what is asyncio
? asyncio
is a library built into Python that’s used to write concurrent code using the async
/await
syntax.
00:11 Let’s just stop for a minute right there. That keyword right there, concurrent—what does it mean? Now, you may think concurrent means at the same time, i.e. running in parallel. Things that are concurrent are tasks or items or work items that could potentially run in parallel, but may not necessarily run in parallel.
00:31
So it’s a way of organizing your code so that it could run in parallel, but not that it necessarily will, okay? So it’s a library used to run code that could potentially run in parallel using this async
/await
syntax.
00:45
asyncio
is often a perfect fit for IO-bound and high-level structured network code. So there’s another keyword here, IO-bound. What does that mean?
00:54 It means if you have an application where the performance of your application is dependent or mostly dependent on IO—so you have an application and you’re doing a lot of IO, and the reason it’s slow is because of that IO—that’s an IO-bound app.
01:12
And so if you are in that situation where you have this app, it’s using a lot of IO, it’s slow, then asyncio
can help you with that and make your application run a lot faster.
01:24
Now, if your code is CPU-bound, consider using the multiprocessing
library instead. So, in Python it obviously has the asyncio
library, it has a library called multiprocessing
. Where you’d want to use multiprocessing is if you’re doing a lot of things that did not involve IO.
01:40
Let’s imagine you were finding prime numbers, like, thousands of different prime numbers, for example. Those would all be running inside the CPU, using the memory and the CPU together, and because it wouldn’t be external to the CPU, then if you were to use asyncio
in a case like finding primes, for example, that wouldn’t do you any good and it wouldn’t be any faster.
02:03
multiprocessing
allows you to actually create different processes, so if you have some code that’s slow and it’s slow because of the CPU, you can create more processes using the multiprocessing
library.
02:16
If your code is slow because you’re doing a lot of IO—you’re reading to the file system, you’re reading to a database, you are talking to an HTTP, like a website—if it’s slow because of that, then you can use asyncio
.
Become a Member to join the conversation.