Python MultiThread Template

I work a lot with Python, from backend implementations consisting of thousands of lines of code, to simple scripts to get things done easier.

I figured I would share my simple template for creating multi-threaded applications. This is very helpful for spawning off x number of threads to do the task you require, to get everything done a whole lot faster. Here it is below:

import socket
import threading
import thread
import asyncore

def Runner(threadid):
	print 'Thread %s started!' % threadid

if __name__ == "__main__":
    print 'Main Running...'
    threadid = 0
    for i in range(1,500):
    	print '%s id started...' % threadid
        threading.Thread(target=Runner, args=(str(i),)).start()
        threadid = threadid + 1

The “__main__” portion starts off the threads. As you can see in the loop, it will start off 500 (well, 499 I guess) and provide each with its own Thread ID. (Useful for tracking outputs). All the code to be run in the thread should be in the Runner function.

I hope this is useful to some, it sure is a nice starting point for things I do!

Leave a Reply