The basics of threading in Python

If you’re a frequent reader of my website, you’ll know that I’ve been doing a lot with Golang recently.. like, a lot and it got me thinking about how easy concurrency is in Golang and how it just isn’t the same in Python.

Below, we have an example of a simple for loop being threaded in Python. Here, the target is the function name and the argument is the name of the thing we want to pass to the function. In this case, it’s the filename.

from threading import *

def clean(file):
    print(file)

       
files = ['original.csv', 'original2.csv', 'original3.csv']


for file in files: 
    x = threading.Thread(target = clean, args = (file,))
    x.start()

Another thing we could do is below. Here, we have two classes. We pass Thread into those classes to let them know that they should be threaded. It’s important to note that the function names here must be run.

We then create instances of the classes and then use .start() to start the multi threaded running of the two functions. The output of this is a really mixed list of names between Bob and Marketeer (as they’re running at the same time, the names are mixed up).

from threading import *
from time import sleep

class print_name(Thread):
    #function MUST be called run
    def run(self):
        for i in range(100):
            sleep(1)
            print("Bob")
            
class print_job(Thread):
    #function MUST be called run
    def run(self):
        for i in range(100):
            sleep(1)
            print("Marketeer")
            
h1 = print_name()
h2 = print_job()

h1.start()
h2.start()