python之threading模块

来自虫师的学习笔记,原地址http://www.cnblogs.com/fnng/p/3670789.html

1、未使用threading模块,电脑先进行听音乐,后看电影,均进行两次

from time import ctime, sleep


def music(song):
    '''listening to a music 2 times,everytime lasts 1 seconds'''
    for r in range(2):
        print 'i\'m listing to \'{}\' at {}.'.format(song, ctime())
        sleep(1) 


def movie(film):
    '''watching movie 2 times,everytime lasts 3 seconds'''
    for r in range(2):
        print 'i\'m watching \'{}\' at {}'.format(film, ctime())
        sleep(3)


if __name__ == '__main__':
    music('heal the world')
    movie('brave heart')
    print 'it\'s time to sleep {}'.format(ctime())

  

 

运行结果如下,先进行听音乐操作后,再次进行看电影操作,看完电影即去睡觉   

i'm listing to 'heal the world' at Tue Oct 17 11:42:02 2017.
i'm listing to 'heal the world' at Tue Oct 17 11:42:03 2017.
i'm watching 'brave heart' at Tue Oct 17 11:42:04 2017
i'm watching 'brave heart' at Tue Oct 17 11:42:07 2017
it's time to sleep Tue Oct 17 11:42:10 2017

2、引入python中threading模块,使听音乐、看电影同时进行:

import threading
from time import ctime,sleep


def music(song):
    '''listening to a music 2 times,everytime lasts 1 seconds'''
    for r in range(2):
        print 'i\'m listing to \'{}\' at {}.'.format(song,ctime())
        sleep(1)

def movie(film):
    '''watching movie 2 times,everytime lasts 3 seconds'''
    for r in range(2):
        print 'i\'m watching \'{}\' at {}'.format(film,ctime())
        sleep(3)

threads=[]
t1=threading.Thread(target=music,args=(u'heal the world',))
threads.append(t1)
t2=threading.Thread(target=movie,args=(u'brave heart',))
threads.append(t2)

if __name__=='__main__':
    for t in threads:
        t.setDaemon(True)
        t.start()
    print 'it\'s time to sleep {}'.format(ctime())

  运行结果如下,可知听音乐、看电影、睡觉都是在同一时刻完成。其中,setDaemon(True)将线程声明为守护线程,需要在start()方法前设置,如果不声明守护线程,程序将会被无限挂起。子线程启动后,父线程也会一并执行下去,执行到最后一句print 'it\'s time to sleep {}'.format(ctime()),没有等待子线程,就会直接退出,同时子线程也会一并结束。

i'm listing to 'heal the world' at Tue Oct 17 15:54:34 2017.
i'm watching 'brave heart' at Tue Oct 17 15:54:34 2017
it's time to sleep Tue Oct 17 15:54:34 2017

查看threading模块的说明书,注意在使用threading.thread模块,参数args为元组(‘tuple’),因此使用时候须为元组格式:

 

3、优化程序,将子线程与父线程分开,使得每个子线程均执行

···

if __name__=='__main__':
    for t in threads:
        t.setDaemon(True)
        t.start()

    t.join()

    print 'it\'s time to sleep {}'.format(ctime())

  运行结果如下,t.join()保证在子线程被执行前,父线程将一直处于阻塞状态。join()方法放在for循环后,则必须执行完子线程才会执行父线程

i'm listing to 'heal the world' at Tue Oct 17 16:16:02 2017.
i'm watching 'brave heart' at Tue Oct 17 16:16:02 2017
i'm listing to 'heal the world' at Tue Oct 17 16:16:03 2017.
i'm watching 'brave heart' at Tue Oct 17 16:16:05 2017
it's time to sleep Tue Oct 17 16:16:08 2017

 总结

线程的简单使用方法为:

1、先创建一个空的列表threads存放即将处理的线程

2、创建子线程使用threading.Thread方法,并添加到列表threads中

3、使用for循环来遍历每个线程,注意使用setDaemon()方法和join()方法(setDaemon(True)用于声明线程为守护线程,join方法确认执行完所有子线程再去执行父线程)

posted @ 2017-10-17 16:20  cuisygan  阅读(254)  评论(0)    收藏  举报