python multithreading + callback

http://www.runoob.com/python/python-multithreading.html

import time
import threading

def main(num, callback):
    print "Start"
    longtime(callback, num)
    print "End"

def longtime(func, num):
    time.sleep(5)
    func(num)

def callback(num):
    print num

def main2(num, callback):
    print "Main Start"

    thread1 = myThread(1, "Thread-1", 1, num, callback)
    thread1.start()
    thread2 = myThread(2, "Thread-2", 2, num+1, callback)
    thread2.start()
    #main(num, callback)
    print "Main End"
    


class myThread(threading.Thread):
    def __init__(self, threadID, name, counter, num, func):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
        self.num = num
        self.func = func
    def run(self):
        print "Starting " + self.name
        time.sleep(5)
        self.func(self.num)
        print "Exiting " + self.name

main2(1000, callback)

Leave a Reply

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