DEV Community

loading...

Threading in Python

documentednerd profile image Kevin Mack Originally published at welldocumentednerd.com 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))
    t.start()
    threadList.append(t)

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:
    t.join()

Enter fullscreen mode Exit fullscreen mode

That’s really it, overall pretty easy.

Discussion (0)

pic
Editor guide