DEV Community


Threading in Python

Kevin Mack
I am a well documented nerd and software developer.
Originally published at on ・1 min read

Just another quick tip and trick for Python, and that is how you implement threading. This is surprisingly simple in Python, but basically it involves installing the threading library using pip

pip install threading

Enter fullscreen mode Exit fullscreen mode

From there the process is the following:

numThreads = 10
threadList = []

def RunTest(self, name):
    print(f"Hello {name}")

for x in range(numThreads):
    t = threading.Thread(target=RunTest, args=(x))

Enter fullscreen mode Exit fullscreen mode

This will then kick off each thread and let them run in the background, now the next logical question being how do I wait for a thread to complete, and that would be the following:

for t in threadList:

Enter fullscreen mode Exit fullscreen mode

That’s really it, overall pretty easy.

Discussion (0)