contact Me

Use the form on the right to send a direct email to my pocket. 


123 Street Avenue, City Town, 99999

(123) 555-6789


You can set your address, phone number, email and site description in the settings tab.
Link to read me page with more information.

Python Multithreaded

Python Multithreading 

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 exampleDefine 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.