Concurrent Programming in Python
Explore how to implement concurrent programming in Python through threading and asyncio. Understand how threads run separate flows of execution and how async functions can run cooperatively with event loops. Learn the differences between threads and coroutines and their impact on concurrency within REST APIs built with Python.
We'll cover the following...
Concurrency using threading
We can implement concurrency in python using the concepts of threads. A thread is a separate flow of execution. This means that your program will have two things happening at once. But for most Python 3 implementations, the different threads do not actually execute at the same time, they merely appear to. This is the reason we are using the term concurrency here instead of parallel processing. You can achieve that too using multiprocessing, which comes with some extra overhead.
Let’s look at an example of concurrency using threads.
Explanation
-
On lines 1 and 2, we import the packages
threadingandtime. -
On line 4, we define a function that will execute three times and has a sleep of
1second. -
On line 9, a similar function is defined but with a ...