In Python you can create threads using the thread module in Python 2.x or _thread module in Python 3. We will use the threading module to interact with it.
A thread is an operating system process with different features than a normal process:
- threads exist as a subset of a process
- threads share memory and resources
- processes have a different address space (in memory)
When would you use threading? Usually when you want a function to occur at the same time as your program. If you create server software, you want the server not only listens to one connection but to many connections. In short, threads enable programs to execute multiple tasks at once.
- Complete Python Bootcamp: Go from zero to hero in Python
- Automate the Boring Stuff with Python Programming
Let’s create a thread program. In this program we will start 10 threads which will each output their id.
Threads do not have to stop if run once. Threads could be timed, where a threads functionality is repeated every x seconds.
In Python, the Timer class is a subclass of the Thread class. This means it behaves similar. We can use the timer class to create timed threads. Timers are started with the .start() method call, just like regular threads. The program below creates a thread that starts after 5 seconds.
Repeating functionality using threads
We can execute threads endlessly like this: