Threading in Python

Threading in Python

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

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)

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()

That’s really it, overall pretty easy.

Leave a Reply

Your email address will not be published. Required fields are marked *