python 中threading的运用

来源:互联网 发布:马尔科夫转移矩阵 编辑:程序博客网 时间:2024/05/19 23:16
#coding = utf-8
import threading
from time import sleep,ctime


loops = [4,2]


def loop(nloop, nsec):
    print 'start loop', nloop, 'at:', ctime()
    sleep(nsec)
    print 'loop', nloop, 'done at:', ctime()


def main():
    #输出starting表示开始,并输出开始时间
    print 'starting at:',ctime()
    #建立一个空数组,存储
    threads = []
    nloops = range(len(loops))
    #创建线程
    for i in nloops:
        t = threading.Thread(target = loop,args=(i,loops[i]))
        threads.append(t)
    #开始线程
    for i in nloops:
        #start()开始线程活动
        threads[i].start()


    #等待所有线程结束
    for i in nloops:
        #join等待线程终止
        threads[i].join()
    #输出最后时间   
    print 'all end:',ctime()


if __name__ == '__main__':
    main()
原创粉丝点击