Problems with threads
Explore the challenges associated with using threads in Python concurrency. Understand shared memory conflicts, the implications of the global interpreter lock, and overhead costs. This lesson helps you recognize threading pitfalls and introduces safer synchronization and alternatives for concurrent programming.
We'll cover the following...
Threads can be useful if appropriate care is taken to manage shared memory, but modern Python programmers tend to avoid them for several reasons. As we’ll see, there are other ways to code concurrent programming that are receiving more attention from the Python community. Let’s discuss some of the pitfalls before moving on to alternatives to multithreaded applications.
Shared memory
The main problem with threads is also their primary advantage. Threads have access to all the process memory and thus all the variables. A disregard for the shared state can too easily cause inconsistencies.
Have you ever encountered a room where a single light has two switches and two different people turn them on at the same time? Each person (thread) expects their action to turn the lamp (a variable) on, but the resulting value (the lamp) is off, which is inconsistent with those expectations. Now imagine if those two threads were ...