一、没有线程的支持的例子:
#!/usr/bin/env python from time import sleep,ctime def loop0(): print 'start loop 0 at:',ctime() sleep(4) print 'loop 0 done at:',ctime() def loop1(): print 'start loop 1 at:',ctime() sleep(2) print 'loop 1 done at:',ctime() def main(): print 'starting at:',ctime() loop0() loop1() print 'all Done at:',ctime() if __name__ == '__main__': main()
运行结果
starting at: Sun Dec 20 15:27:45 2015 start loop 0 at: Sun Dec 20 15:27:45 2015 loop 0 done at: Sun Dec 20 15:27:49 2015 start loop 1 at: Sun Dec 20 15:27:49 2015 loop 1 done at: Sun Dec 20 15:27:51 2015 all Done at: Sun Dec 20 15:27:51 2015 [Finished in 6.0s]
在单线程中执行两个循环。当一个循环结束后,另一个才能开始。总时间是各个循环时间之和
二、thread
#!/usr/bin/env python import thread from time import sleep,ctime def loop0(): print 'start loop0 at:',ctime() sleep(4) print 'loop0 done at:',ctime() def loop1(): print 'start loop1 at:',ctime() sleep(2) print 'loop1 done at:',ctime() def main(): print 'starting at:',ctime() thread.start_new_thread(loop0,()) thread.start_new_thread(loop1,()) sleep(6) print 'all done at:',ctime() if __name__ == '__main__': main()
运行结果:
starting at: Sun Dec 20 15:43:09 2015 start loop0 at: Sun Dec 20 15:43:09 2015 start loop1 at: Sun Dec 20 15:43:09 2015 loop1 done at: Sun Dec 20 15:43:11 2015 loop0 done at: Sun Dec 20 15:43:13 2015 all done at: Sun Dec 20 15:43:15 2015 [Finished in 6.0s]
注意:start_new_thread()要求一定要有前两个参数,所以,就算我们想要运行的函数不需要参数,我们也要传一个空的元组
睡眠的4秒和2秒代码现在是并发执行的,这样就使得总的运行时间被缩短了,可以看到loop1甚至再loop0之前就结束了,为什么要加上
sleep(6)? 原因是:因为如果我们没有让主线程停下来,那么主线程就会运行下一条语句,显示『all done』,然后就关闭运行着loop0,loop1的两个线程
退出了。
三、使用线程和锁
#!/usr/bin/env python #--*-- coding:utf-8 --*-- import thread from time import sleep,ctime loops = [4,2] def loop(nloop,nsec,lock): print 'start loop',nloop,'at:',ctime() sleep(nsec) print 'loop',nloop,'done at:',ctime() lock.release() def main(): print 'starting at:',ctime() locks = [] nloops = range(len(loops)) for i in nloops: lock = thread.allocate_lock() lock.acquire() locks.append(lock) for i in nloops: thread.start_new_thread(loop,(i,loops[i],locks[i])) for i in nloops: while locks[i].locked():pass print 'all done at:',ctime() if __name__ == '__main__': main()