python 多线程编程(一)

传统的python单线程程序:

'''
Created on 2012-3-9

@author: Administrator
'''
#!/usr/bin/env python

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 'start  at:',ctime()
    loop0()
    loop1()
    print 'All done at:',ctime()
    
if __name__=='__main__':
    main()
运行结果:

start  at: Fri Mar 09 16:28:12 2012
start loop0 at: Fri Mar 09 16:28:12 2012
loop0 done at: Fri Mar 09 16:28:16 2012
start loop1 at: Fri Mar 09 16:28:16 2012
loop1 done at: Fri Mar 09 16:28:18 2012
All done at: Fri Mar 09 16:28:18 2012
可见程序是顺序执行。

多线程例子:

'''
Created on 2012-3-9

@author: Administrator
'''
#!/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 'start  at:',ctime()
    thread.start_new_thread(loop0, ())
    thread.start_new_thread(loop1, ())
    sleep(6)
    print 'All done at:',ctime()
    
if __name__=='__main__':
    main()



运行结果:

start  at: Fri Mar 09 16:35:27 2012
start loop0 at: Fri Mar 09 16:35:27 2012
start loop1 at: Fri Mar 09 16:35:27 2012
loop1 done at: Fri Mar 09 16:35:29 2012
loop0 done at: Fri Mar 09 16:35:31 2012
All done at: Fri Mar 09 16:35:33 2012
可见
loop0 的执行和
loop1是并行的,一共三个线程:主线程、运行loop0的线程和运行loop1的线程。




你可能感兴趣的:(python)