Python 多线程就这么简单
来源:Linux社区 作者:StitchSun
多线程和多进程是什么自行google补脑
对于Python 多线程的理解,我花了很长时间,搜索的大部份文章都不够通俗易懂。所以,这里力图用简单的例子,让你对多线程有个初步的认识。
单线程
在好些年前的MS-DOS时代,操作系统处理问题都是单任务的,我想做听音乐和看电影两件事儿,那么一定要先排一下顺序。
(好吧!我们不纠结在DOS时代是否有听音乐和看影的应用。^_^)
1 from time import ctime,sleep
2
3 def music():
4 for i in range(2):
5 print "I was listening to music. %s" %ctime()
6 sleep(1)
7
8 def move():
9 for i in range(2):
10 print "I was at the movies! %s" %ctime()
11 sleep(5)
12
13 if __name__ == '__main__':
14 music()
15 move()
16 print "all over %s" %ctime()
我们先听了一首音乐,通过for循环来控制音乐的播放了两次,每首音乐播放需要1秒钟,sleep()来控制音乐播放的时长。接着我们又看了一场电影,
每一场电影需要5秒钟,因为太好看了,所以我也通过for循环看两遍。在整个休闲娱乐活动结束后,我通过
print "all over %s" %ctime()
看了一下当前时间,差不多该睡觉了。
运行结果:
>>=========================== RESTART ================================
>>>
I was listening to music. Thu Apr 17 10:47:08 2014
I was listening to music. Thu Apr 17 10:47:09 2014
I was at the movies! Thu Apr 17 10:47:10 2014
I was at the movies! Thu Apr 17 10:47:15 2014
all over Thu Apr 17 10:47:20 2014
其实,music()和move()更应该被看作是音乐和视频播放器,至于要播放什么歌曲和视频应该由我们使用时决定。所以,我们对上面代码做了改造:
1 #coding=utf-8
2 import threading
3 from time import ctime,sleep
4
5 def music(func):
6 for i in range(2):
7 print "I was listening to %s. %s" %(func,ctime())
8 sleep(1)
9
10 def move(func):
11 for i in range(2):
12 print "I was at the %s! %s" %(func,ctime())
13 sleep(5)
14
15 if __name__ == '__main__':
16 music(u'爱情买卖')
17 move(u'阿凡达')
18
19 print "all over %s" %ctime()
对music()和move()进行了传参处理。体验中国经典歌曲和欧美大片文化。
运行结果:
>>> ======================== RESTART ================================
>>>
I was listening to 爱情买卖. Thu Apr 17 11:48:59 2014
I was listening to 爱情买卖. Thu Apr 17 11:49:00 2014
I was at the 阿凡达! Thu Apr 17 11:49:01 2014
I was at the 阿凡达! Thu Apr 17 11:49:06 2014
all over Thu Apr 17 11:49:11 2014
多线程
科技在发展,时代在进步,我们的CPU也越来越快,CPU抱怨,P大点事儿占了我一定的时间,其实我同时干多个活都没问题的;于是,操作系统就进入了多任务时代。我们听着音乐吃着火锅的不在是梦想。
python提供了两个模块来实现多线程thread 和threading ,thread 有一些缺点,在threading 得到了弥补,为了不浪费你和时间,所以我们直接学习threading 就可以了。
继续对上面的例子进行改造,引入threadring来同时播放音乐和视频:
1 #coding=utf-8
2 import threading
3 from time import ctime,sleep
4
5 def music(func):
6 for i in range(2):
7 print "I was listening to %s. %s" %(func,ctime())
8 sleep(1)
9
10 def move(func):
11 for i in range(2):
12 print "I was at the %s! %s" %(func,ctime())
13 sleep(5)
14
15 threads = []
16 t1 = threading.Thread(target=music,args=(u'爱情买卖',))
17 threads.append(t1)
18 t2 = threading.Thread(target=move,args=(u'阿凡达',))
19 threads.append(t2)
20
21 if __name__ == '__main__':
22 for t in threads:
23 t.setDaemon(True)
24 t.start()
25
26 print "all over %s" %ctime()