Member-only story
Thread Your Python Program with Two Lines of Code
Speed up your program by doing multiple things simultaneously
When your program has a lot of tasks that involve waiting you can speed up your program by executing those tasks simultaneously instead of one by one. When making breakfast you don’t wait for the coffee machine to finish before cooking an egg. Instead you flick on the coffee maker and pour yourself a cup of orange juice while heating up the pan for the scrambled eggs.
This article shows you how to do precisely that. At the end you’ll be able to safely apply threading in 2 lines of code and achieve a huge speedup in your program. Let’s code!
But first..
This article will detail how to apply threads by applying the same function to a whole list of arguments. Then we’ll check out how to apply different functions in a threaded way.
Are threads going to solve my problem? Understanding concurrency
It is true that in many cases your program can be sped up by doing “multiple things at the same time” but blindly applying threads everywhere isn’t a smart solution. There are two ways to multi-task in Python: multiprocessing and threading:
- threading runs code concurrently: we have one active CPU that quickly switches between multiple threads
- multiprocessing runs code in parallel: we have multiple active CPU’s that each run their own code (check out the article below)
When threading you have one actor that executes all tasks simultaneously by switching between them. In the context of the breakfast-example from the intro: there is one actor (you) that switches between the coffee…