Raymond Klucik - March 16th 2016
Sometimes you need to spin off tasks to be done in the background so your main task continues to run. If you were to have a music application, such as Spotify, playing your music you'd want it to be seamless and play your next track immediately after the current one should you press 'skip'. This is where multithreading is useful; while the main program processes the current file it sends another thread to fetch the next song. Doing this is efficient and is more efficient in distributing CPU.
Setting up a multithreaded application can be done using the threading module. We need to import Thread from the threading class in addition to the time class so that we can print the duration of each timer. We create our 2 threads in main, t1 and t2, and pass a target function to each of them. Our target function, timer requires 3 arguments; (name, delay, repeat) which we set to the values seen below so that we have an overlap in our threads making it a true multithreaded example. Define the timer function and pass the parameters. We use ctime to print the time in c-format which is easier to work with in Python code.
After we have defined the target function and set up the timers we need to tell them to start in main() and this is where the two threads will actually start and loop through the printing commands. The threads will run in the background as two separate processes and will finish after the main program.