Thursday, January 12, 2012

[Level 3] Multithread in Python

#!/bin/env python
import os, sys
import threading
import random

class ThreadClass (threading.Thread):
    def __init__(self, function, seconds, threads):
        self.function = function
        self.seconds = seconds
        threading.Thread.__init__(self)
        threads.append(self)
     
    def run(self):
        print 'run %s...' % self.seconds
        self.function(self.seconds)
        print 'run %s done!' % self.seconds

class TestMultiThread(object):
    def __init__(self):
        self.max_thread = 5 
        self.threads = []
        pass

    def task(self, seconds):
        os.popen('sleep %s' % seconds).read()

    def run(self):
        for i in range(0, self.max_thread):
            seconds = int(random.random() * 10) 
            ThreadClass(self.task, seconds, self.threads).start()

        for t in self.threads:
            t.join()

        print 'Jobs done!'

if __name__ == '__main__':
    tmt = TestMultiThread()
    tmt.run()

$ ./testMultiThread.py 
run 1...
run 9...
run 2...
run 7...
run 1...
run 1 done!
run 1 done!
run 2 done!
run 7 done!
run 9 done!
Jobs done!
$
Wish this helps. regards, Stanley Huang