Python 多线程

一、单线程的时代

在单线程时代,当处理器需要处理多个任务时,必须对这些任务安排执行顺序,并按照这个顺序来执行任务。假如我们创建了两个任务:听音乐(music)和看电影(movie),在单线程中,我们只能按照先后顺序来执行这两个任务,下面就通过一个例子来演示。

#!usr/bin/env python
#coding:utf-8

from time import sleep,ctime

#听音乐任务
def music():
    print('I was listen to music!%s' %ctime())

#看电影任务
def movie():
    print('I was at the movies!%s' %ctime())


if __name__ == '__main__':
    music()
    movie()
    print('all end:',ctime())

 

 

二、多线程技术(threading)

#!usr/bin/env python
#coding:utf-8

from time import sleep,ctime
import threading

#音乐播放器
def music(func,loop):
    for i in range(loop):
        print('I was listen to %s! %s' %(func,ctime()))

#电影播放器
def movie(func,loop):
    for i in range(loop):
        print('I was at the %s! %s' %(func,ctime()))


#创建线程组,用于装线程
threads = []

#创建线程t1,并添加到线程组
t1 = threading.Thread(target=music,args=('纸短情长',3))
threads.append(t1)


#创建线程t2,并添加到线程组
t2 = threading.Thread(target=movie,args=('生化危机',5))
threads.append(t2)

if __name__ == '__main__':
    #启动线程
    for t in threads:
        t.start()

    #守护线程
    for t in threads:
        t.join()
    print('all end %s' %ctime())

 

注意:如果不用join()对于每个执行的线程进行守护,则在所有线程执行过程中回去执行最终的all end。

 

posted @ 2018-06-05 14:25  我是旺旺  阅读(114)  评论(0编辑  收藏  举报