Intermediate tutorial in python 3)Python Threading

<< Previous – Classes and OOP

Working with threads in python is something that’s very useful for certain applications where you need to perform many things at once or in parallel independent of each other in some cases. For instance, let’s say you needed to write a script that constantly streamed data to the console, but also received user input to configure that data. You might be thinking, that’s easy, I can just put everything in an infinite while loop and be done with it. Sure, that will work to some extent, but let’s say the requirement is to have a 2 second delay every time you print the data to the console? You’d eventually start missing user input, because the user might enter a value during those 2 seconds.

My Freelance Paycheck – Start Your Freelance Career Online Today!

You may have read about the nature of threading in python in other books or tutorials and realize already that python threading isn’t true threading in the sense that under the hood it’s just context switching between tasks, which gives you functionality that is very close to threading but not necessarily the textbook definition of threading. I won’t go into detail here, as the purpose of this tutorial is to get you writing python threads. Just know that python threading is different from say, C++/C# threading.

It’s fairly easy to define and instantiate a Thread in python. Consider this simple example:

from threading import Thread

def threadOneFunction():
print("ThreadOneFunction running...")

def threadTwoFunction():
print("ThreadTwoFunction running...")

if __name__ == '__main__':
print("Starting...")
t1 = Thread(target=threadOneFunction)
t2 = Thread(target=threadTwoFunction)
t1.start()
t2.start()
t1.join()
t2.join()
print("Done.")

Tutor Jobs Online! Become an Online Tutor Today.

In this example, you have two types of threads that are possible. One can be instantiated using the threadOneFunction() function and the other threadTwoFunction(). In this example, we instantiate two threads t1(defined by threadOneFunction) and t2(defined by threadTwoFunction). Instantiation of a Thread in it’s simplest form involves defining the target, as shown in the example above with the format Thread(target=<function or class name>). That’s right, you can define a thread using a class, which may be more appropriate for complex tasks, but since we are only introducing threads here, we will use functions. You call the start() method on every thread when you want to start it. There might be cases where you don’t necessarily want to start a thread at instantiation. Finally, we call join() on each thread so that we block the main calling thread until the thread that we are calling join() on terminates or finishes. Another way of saying this is that if threadOneFunction takes 10 minutes to terminate and threadTwoFunction takes 2 minutes, then it will take 12 minutes for the “Done” print statement to execute in main.

If you’re using PyCharm you can copy this source code into a file and name it threadExample.py:

You can then create a simple run/debug configuration that points to the script path so that you can run this directly in the IDE:


This is the output you should see in pyCharm:

Want To Work From Home? Take This Online Course To Find Out How

Again, this is the absolute simplest example of a thread, and just like everything else in python, there are many different ways to implement the same solution, and a lot to still learn from here. I encourage you to read the python docs on threading to get more out of this: https://docs.python.org/3.6/library/threading.html

Intermediate tutorial in python – 4) Unit Tests >>

2 Comments

Leave a comment