python多线程使用threading模块锁线程

import threading
import time
class mythread(threading.Thread) :
    def __init__(self,func,args,name=''):
        threading.Thread.__init__(self)
        self.func=func
        self.args=args
        self.name=name
    def run(self) :
        apply(self.func,self.args)
def loop(num,sec):
    print "loop%s start at %s" % (num,time.ctime())
    time.sleep(sec)
    print "loop%s stop at %s" % (num,time.ctime())
loops=[1,3]
def main():
    print "all start at %s" % time.ctime()
    threads=[]
    nloops=range(len(loops))
    for i in nloops:
        t=mythread(loop,(i,loops[i]),loop.__name__)
        threads.append(t)
    for i in nloops :
        threads[i].start()
    for i in nloops :
        threads[i].join()
    print "all end at %s" % time.ctime()
if __name__ == '__main__' :
    main()

执行结果:

all start at Tue Feb 12 15:54:24 2013
loop0 start at Tue Feb 12 15:54:24 2013
loop1 start at Tue Feb 12 15:54:24 2013
loop0 stop at Tue Feb 12 15:54:25 2013
loop1 stop at Tue Feb 12 15:54:27 2013
all end at Tue Feb 12 15:54:27 2013

有个地方疑惑,就是,所有进程结束以后,print信息才一次显示出来。我想让子线程执行完了立即显示print信息该怎么写呢?

你可能感兴趣的:(python多线程使用threading模块锁线程)