Concurrency, parallelism and the GIL
A sequential program does one thing after another. But many programs spend most of their time waiting : for a server, a disk, a…
Learn to do several things at once, or to make it look that way. In this lesson you will tell concurrency from parallelism, learn about the GIL, use threads with threading and locks, the concurrent.futures module, queue queues and asyncio coroutines, and see how to avoid race conditions and deadlocks. The browser corrector cannot create real threads, so the exercises simulate schedulers, queues, semaphores, pools and event loops in a deterministic way.
A sequential program does one thing after another. But many programs spend most of their time waiting : for a server, a disk, a…
A thread is a flow of execution inside a process. All the threads of a process share memory (variables, lists…). The threading…
Creating and waiting for threads by hand is tedious and error-prone. The concurrent.futures module offers a higher-level…
asyncio offers concurrency in a single thread . Instead of the operating system switching threads whenever it wants, you decide…
Locks solve race conditions, but they introduce another danger: the deadlock .
Create a Python program that shares time between several tasks in turns ( round-robin ), as a task scheduler does. Each task is a…
Adding processors does not speed up a program indefinitely: the part that cannot be parallelized limits the improvement. Amdahl's…
A race condition happens when several threads read and modify the same data and the result depends on the order in which they…
The producer-consumer pattern connects two parts through a queue with limited capacity. Use queue.Queue(maxsize=...) from the…
A semaphore limits how many threads can use a resource at the same time: it has a number of permits . If none are left, the…
To take advantage of several processors you have to divide the work into independent chunks, process them separately and combine…
A worker pool (like ThreadPoolExecutor ) shares a list of jobs among a fixed number of workers: each job is taken by the first…
This is how asyncio.sleep works inside: an event loop keeps a schedule of sleeping tasks and always wakes up the one that is due…
A deadlock happens when two threads wait forever: each one holds a lock the other one needs. It can be detected in advance : if…
With enough workers, independent tasks run at the same time, but a task cannot start until the ones it depends on have finished…