How to use multiple threads

You should let the main thread stay alive for a little while. If the main thread dies, so will all the other threads and hence you will not see any output. Try adding a time.sleep(0.1) at the end of the code and then you will see the output.

After that, you can have a look at the thread.join() to get more idea about this.


First of all, you should use the higher level threading module and specifically the Thread class. The thread module is not what you need.

As you extend this code, you most likely will also want to wait for the threads to finish. Following is a demonstration of how to use the join method to achieve that:

import threading

class print_out(threading.Thread):

    def __init__ (self, m1, m2):
        threading.Thread.__init__(self)
        self.m1 = m1
        self.m2 = m2

    def run(self):
        print self.m1
        print self.m2
        print "\n"

threads = []
for num in range(0, 10):
    thread = print_out('a', 'b')
    thread.start()
    threads.append(thread)

for thread in threads:
    thread.join()

Using thread module, you need to have a main thread running, by adding a while loop below

import thread

def print_out(m1, m2):
    print m1
    print m2
    print "\n"

for num in range(0, 10):
    thread.start_new_thread(print_out, ('a', 'b'))`

while(1):
    pass

The other approach is using threading class.

 instance[num]=threading.Thread(target=print_out, args=('a', 'b'))

 instance[num].start()