Threads
Learn about concurrent threading and its implementation with the help of a coding example.
We'll cover the following
A thread is a sequence of Python byte-code instructions that may be interrupted and resumed. The idea is to create separate, concurrent threads to allow computation to proceed while the program is waiting for I/O to happen.
Example
For example, a server can start processing a new network request while it waits for data from a previous request to arrive. Or an interactive program might render an animation or perform a calculation while waiting for the user to press a key. Bear in mind that while a person can type more than 500 characters per minute, a computer can perform billions of instructions per second. Thus, a ton of processing can happen between individual key presses, even when typing quickly.
It’s theoretically possible to manage all this switching between activities within your program, but it would be virtually impossible to get right. Instead, we can rely on Python and the operating system to take care of the tricky switching part, while we create objects that appear to be running independently but simultaneously. These objects are called threads.
Defining the thread processing
Let’s take a look at a basic example. We’ll start with the essential definition of the thread’s processing, as shown in the following class:
Get hands-on with 1400+ tech skills courses.