The Python core module Threading provides a really simple way to add concurrency to any program. Concurrency is when a computer executes several instructions simultaneously. If your code waits for a function, but there are other things it could or should be doing in the meantime, try using threading. If threads aren’t quite enough and you feel the need to leverage multiple processors, use the multiprocessing module instead. It is more powerful but also has more overhead to load up.
There are many times where threading is useful, but none so common as a GUI-based program. Python is run sequentially so any little delay will hold up the user interface until the interpreter is done running the other code. For example, a label needs to update to show progress while files are downloaded. If a GUI button calls a function, the whole function has to finish before the interface can regain control and update the window.
Here’s a little example of a timer function that counts up to the specified number of seconds. This is perfect for threading in a GUI so a label can be updated with the current time. After defining the function, a thread is initialized and started up.
1 2 3 4 5 6 7 8 9 10 11 12 |
from threading import Thread import time def run_timer(timer_length=10): start_time = time.time() timer = 0 while timer < timer_length: timer = time.time() - start_time print(timer) my_thread = Thread(target=run_timer, kwargs={'timer_length': 10}) my_thread.start() |
Note how quotes are needed around ‘timer_length’ in the keyword args hash in the Thread constructor, but not in the original function definition.
I haven’t tried any advanced threading setups yet, only basics like downloading emails with imaplib and running a timer for an indicator app. Let me know in the comments if you have any questions or if you thought of any cool uses of threading in your own code!