多线程

古城微笑少年丶 2022-04-11 12:18 34阅读 0赞

单线程

  在好些年前的MS-DOS时代,操作系统处理问题都是单任务的,我想做听音乐和看电影两件事儿,那么一定要先排一下顺序。

(好吧!我们不纠结在DOS时代是否有听音乐和看影的应用。^_^)

复制代码

  1. from time import ctime,sleep
  2. def music():
  3. for i in range(2):
  4. print "I was listening to music. %s" %ctime()
  5. sleep(1)
  6. def move():
  7. for i in range(2):
  8. print "I was at the movies! %s" %ctime()
  9. sleep(5)
  10. if __name__ == '__main__':
  11. music()
  12. move()
  13. print "all over %s" %ctime()

复制代码

复制代码

  我们先听了一首音乐,通过for循环来控制音乐的播放了两次,每首音乐播放需要1秒钟,sleep()来控制音乐播放的时长。接着我们又看了一场电影,

每一场电影需要5秒钟,因为太好看了,所以我也通过for循环看两遍。在整个休闲娱乐活动结束后,我通过

  1. print "all over %s" %ctime()

看了一下当前时间,差不多该睡觉了。

运行结果:

复制代码

复制代码

  1. >>=========================== RESTART ================================
  2. >>>
  3. I was listening to music. Thu Apr 17 10:47:08 2014
  4. I was listening to music. Thu Apr 17 10:47:09 2014
  5. I was at the movies! Thu Apr 17 10:47:10 2014
  6. I was at the movies! Thu Apr 17 10:47:15 2014
  7. 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. def music(func):
  5. for i in range(2):
  6. print "I was listening to %s. %s" %(func,ctime())
  7. sleep(1)
  8. def move(func):
  9. for i in range(2):
  10. print "I was at the %s! %s" %(func,ctime())
  11. sleep(5)
  12. if __name__ == '__main__':
  13. music(u'爱情买卖')
  14. move(u'阿凡达')
  15. print "all over %s" %ctime()

复制代码

复制代码

  对music()和move()进行了传参处理。体验中国经典歌曲和欧美大片文化。

运行结果:

复制代码

复制代码

  1. >>> ======================== RESTART ================================
  2. >>>
  3. I was listening to 爱情买卖. Thu Apr 17 11:48:59 2014
  4. I was listening to 爱情买卖. Thu Apr 17 11:49:00 2014
  5. I was at the 阿凡达! Thu Apr 17 11:49:01 2014
  6. I was at the 阿凡达! Thu Apr 17 11:49:06 2014
  7. 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. def music(func):
  5. for i in range(2):
  6. print "I was listening to %s. %s" %(func,ctime())
  7. sleep(1)
  8. def move(func):
  9. for i in range(2):
  10. print "I was at the %s! %s" %(func,ctime())
  11. sleep(5)
  12. threads = []
  13. t1 = threading.Thread(target=music,args=(u'爱情买卖',))
  14. threads.append(t1)
  15. t2 = threading.Thread(target=move,args=(u'阿凡达',))
  16. threads.append(t2)
  17. if __name__ == '__main__':
  18. for t in threads:
  19. t.setDaemon(True)
  20. t.start()
  21. print "all over %s" %ctime()

复制代码

复制代码

import threading

首先导入threading 模块,这是使用多线程的前提。

threads = []

t1 = threading.Thread(target=music,args=(u’爱情买卖’,))

threads.append(t1)

  创建了threads数组,创建线程t1,使用threading.Thread()方法,在这个方法中调用music方法target=music,args方法对music进行传参。 把创建好的线程t1装到threads数组中。

  接着以同样的方式创建线程t2,并把t2也装到threads数组。

for t in threads:

  t.setDaemon(True)

  t.start()

最后通过for循环遍历数组。(数组被装载了t1和t2两个线程)

setDaemon()

  setDaemon(True)将线程声明为守护线程,必须在start() 方法调用之前设置,如果不设置为守护线程程序会被无限挂起。子线程启动后,父线程也继续执行下去,当父线程执行完最后一条语句print “all over %s” %ctime()后,没有等待子线程,直接就退出了,同时子线程也一同结束。

start()

开始线程活动。

运行结果:

  1. >>> ========================= RESTART ================================
  2. >>>
  3. I was listening to 爱情买卖. Thu Apr 17 12:51:45 2014 I was at the 阿凡达! Thu Apr 17 12:51:45 2014 all over Thu Apr 17 12:51:45 2014

  从执行结果来看,子线程(muisc 、move )和主线程(print “all over %s” %ctime())都是同一时间启动,但由于主线程执行完结束,所以导致子线程也终止。

继续调整程序:

复制代码

复制代码

  1. ...
  2. if __name__ == '__main__':
  3. for t in threads:
  4. t.setDaemon(True)
  5. t.start()
  6. t.join()
  7. print "all over %s" %ctime()

复制代码

复制代码

  我们只对上面的程序加了个join()方法,用于等待线程终止。join()的作用是,在子线程完成运行之前,这个子线程的父线程将一直被阻塞。

  注意: join()方法的位置是在for循环外的,也就是说必须等待for循环里的两个进程都结束后,才去执行主进程。

运行结果:

复制代码

复制代码

  1. >>> ========================= RESTART ================================
  2. >>>
  3. I was listening to 爱情买卖. Thu Apr 17 13:04:11 2014 I was at the 阿凡达! Thu Apr 17 13:04:11 2014
  4. I was listening to 爱情买卖. Thu Apr 17 13:04:12 2014
  5. I was at the 阿凡达! Thu Apr 17 13:04:16 2014
  6. all over Thu Apr 17 13:04:21 2014

复制代码

复制代码

  从执行结果可看到,music 和move 是同时启动的。

  开始时间4分11秒,直到调用主进程为4分22秒,总耗时为10秒。从单线程时减少了2秒,我们可以把music的sleep()的时间调整为4秒。

复制代码

复制代码

  1. ...
  2. def music(func):
  3. for i in range(2):
  4. print "I was listening to %s. %s" %(func,ctime())
  5. sleep(4)
  6. ...

复制代码

复制代码

执行结果:

复制代码

复制代码

  1. >>> ====================== RESTART ================================
  2. >>>
  3. I was listening to 爱情买卖. Thu Apr 17 13:11:27 2014I was at the 阿凡达! Thu Apr 17 13:11:27 2014
  4. I was listening to 爱情买卖. Thu Apr 17 13:11:31 2014
  5. I was at the 阿凡达! Thu Apr 17 13:11:32 2014
  6. all over Thu Apr 17 13:11:37 2014

复制代码

复制代码

  子线程启动11分27秒,主线程运行11分37秒。

  虽然music每首歌曲从1秒延长到了4 ,但通多程线的方式运行脚本,总的时间没变化。

本文从感性上让你快速理解python多线程的使用,更详细的使用请参考其它文档或资料。

==========================================================

class threading.Thread()说明:

class threading.Thread(group=None, target=None, name=None, args=(), kwargs={})

This constructor should always be called with keyword arguments. Arguments are:

  group should be None; reserved for future extension when a ThreadGroup class is implemented.

  target is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called.

  name is the thread name. By default, a unique name is constructed of the form “Thread-N” where N is a small decimal number.

  args is the argument tuple for the target invocation. Defaults to ().

  kwargs is a dictionary of keyword arguments for the target invocation. Defaults to {}.

If the subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.__init__()) before doing

anything else to the thread.

  1. 是不是感觉感觉讲的意犹未尽,其实,多线程非常有意思。因为我们在使用电脑的过程中无时无刻都在多进程和多线程。我们可以接着之前的例子继续讲:

  从上面例子中发现线程的创建是颇为麻烦的,每创建一个线程都需要创建一个tx(t1、t2、…),如果创建的线程多时候这样极其不方便。下面对通过例子进行继续改进:

player.py

复制代码

复制代码

  1. #coding=utf-8
  2. from time import sleep, ctime
  3. import threading
  4. def muisc(func):
  5. for i in range(2):
  6. print 'Start playing: %s! %s' %(func,ctime())
  7. sleep(2)
  8. def move(func):
  9. for i in range(2):
  10. print 'Start playing: %s! %s' %(func,ctime())
  11. sleep(5)
  12. def player(name):
  13. r = name.split('.')[1]
  14. if r == 'mp3':
  15. muisc(name)
  16. else:
  17. if r == 'mp4':
  18. move(name)
  19. else:
  20. print 'error: The format is not recognized!'
  21. list = ['爱情买卖.mp3','阿凡达.mp4']
  22. threads = []
  23. files = range(len(list))
  24. #创建线程
  25. for i in files:
  26. t = threading.Thread(target=player,args=(list[i],))
  27. threads.append(t)
  28. if __name__ == '__main__':
  29. #启动线程
  30. for i in files:
  31. threads[i].start()
  32.  for i in files:
  33.    threads[i].join()
  34. #主线程
  35. print 'end:%s' %ctime()

复制代码

复制代码

  有趣的是我们又创建了一个player()函数,这个函数用于判断播放文件的类型。如果是mp3格式的,我们将调用music()函数,如果是mp4格式的我们调用move()函数。哪果两种格式都不是那么只能告诉用户你所提供有文件我播放不了。

  然后,我们创建了一个list的文件列表,注意为文件加上后缀名。然后我们用len(list) 来计算list列表有多少个文件,这是为了帮助我们确定循环次数。

  接着我们通过一个for循环,把list中的文件添加到线程中数组threads[]中。接着启动threads[]线程组,最后打印结束时间。

  1. split()可以将一个字符串拆分成两部分,然后取其中的一部分。

复制代码

复制代码

  1. >>> x = 'testing.py'
  2. >>> s = x.split('.')[1]
  3. >>> if s=='py':
  4. print s
  5. py

复制代码

复制代码

运行结果:

  1. Start playing 爱情买卖.mp3! Mon Apr 21 12:48:40 2014
  2. Start playing 阿凡达.mp4! Mon Apr 21 12:48:40 2014
  3. Start playing 爱情买卖.mp3! Mon Apr 21 12:48:42 2014
  4. Start playing 阿凡达.mp4! Mon Apr 21 12:48:45 2014
  5. end:Mon Apr 21 12:48:50 2014

现在向list数组中添加一个文件,程序运行时会自动为其创建一个线程。

继续改进例子:

  通过上面的程序,我们发现player()用于判断文件扩展名,然后调用music()和move() ,其实,music()和move()完整工作是相同的,我们为什么不做一台超级播放器呢,不管什么文件都可以播放。经过改造,我的超级播放器诞生了。

super_player.py

复制代码

复制代码

  1. #coding=utf-8
  2. from time import sleep, ctime
  3. import threading
  4. def super_player(file,time):
  5. for i in range(2):
  6. print 'Start playing: %s! %s' %(file,ctime())
  7. sleep(time)
  8. #播放的文件与播放时长
  9. list = {'爱情买卖.mp3':3,'阿凡达.mp4':5,'我和你.mp3':4}
  10. threads = []
  11. files = range(len(list))
  12. #创建线程
  13. for file,time in list.items():
  14. t = threading.Thread(target=super_player,args=(file,time))
  15. threads.append(t)
  16. if __name__ == '__main__':
  17. #启动线程
  18. for i in files:
  19. threads[i].start()
  20.   for i in files:
  21.    threads[i].join()
  22. #主线程
  23. print 'end:%s' %ctime()

复制代码

复制代码

  首先创建字典list ,用于定义要播放的文件及时长(秒),通过字典的items()方法来循环的取file和time,取到的这两个值用于创建线程。

  接着创建super_player()函数,用于接收file和time,用于确定要播放的文件及时长。

  最后是线程启动运行。运行结果:

复制代码

复制代码

  1. Start playing 爱情买卖.mp3! Fri Apr 25 09:45:09 2014
  2. Start playing 我和你.mp3! Fri Apr 25 09:45:09 2014
  3. Start playing 阿凡达.mp4! Fri Apr 25 09:45:09 2014
  4. Start playing 爱情买卖.mp3! Fri Apr 25 09:45:12 2014
  5. Start playing 我和你.mp3! Fri Apr 25 09:45:13 2014
  6. Start playing 阿凡达.mp4! Fri Apr 25 09:45:14 2014
  7. end:Fri Apr 25 09:45:19 2014

复制代码

复制代码

创建自己的多线程类

复制代码

复制代码

  1. #coding=utf-8
  2. import threading
  3. from time import sleep, ctime
  4. class MyThread(threading.Thread):
  5. def __init__(self,func,args,name=''):
  6. threading.Thread.__init__(self)
  7. self.name=name
  8. self.func=func
  9. self.args=args
  10. def run(self):
  11. apply(self.func,self.args)
  12. def super_play(file,time):
  13. for i in range(2):
  14. print 'Start playing: %s! %s' %(file,ctime())
  15. sleep(time)
  16. list = {'爱情买卖.mp3':3,'阿凡达.mp4':5}
  17. #创建线程
  18. threads = []
  19. files = range(len(list))
  20. for k,v in list.items():
  21. t = MyThread(super_play,(k,v),super_play.__name__)
  22. threads.append(t)
  23. if __name__ == '__main__':
  24. #启动线程
  25. for i in files:
  26. threads[i].start()
  27.   for i in files:
  28.    threads[i].join()
  29. #主线程
  30. print 'end:%s' %ctime()

复制代码

复制代码

MyThread(threading.Thread)

创建MyThread类,用于继承threading.Thread类。

__init__()

使用类的初始化方法对func、args、name等参数进行初始化。

apply()

  apply(func [, args [, kwargs ]]) 函数用于当函数参数已经存在于一个元组或字典中时,间接地调用函数。args是一个包含将要提供给函数的按位置传递的参数的元组。如果省略了args,任何参数都不会被传递,kwargs是一个包含关键字参数的字典。

apply() 用法:

复制代码

复制代码

  1. #不带参数的方法
  2. >>> def say():
  3. print 'say in'
  4. >>> apply(say)
  5. say in
  6. #函数只带元组的参数
  7. >>> def say(a,b):
  8. print a,b
  9. >>> apply(say,('hello','虫师'))
  10. hello 虫师
  11. #函数带关键字参数
  12. >>> def say(a=1,b=2):
  13. print a,b
  14. >>> def haha(**kw):
  15. apply(say,(),kw)
  16. >>> haha(a='a',b='b')
  17. a b

复制代码

复制代码

MyThread(super_play,(k,v),super_play.__name__)

由于MyThread类继承threading.Thread类,所以,我们可以使用MyThread类来创建线程。

运行结果:

  1. Start playing 爱情买卖.mp3! Fri Apr 25 10:36:19 2014
  2. Start playing 阿凡达.mp4! Fri Apr 25 10:36:19 2014
  3. Start playing 爱情买卖.mp3! Fri Apr 25 10:36:22 2014
  4. Start playing 阿凡达.mp4! Fri Apr 25 10:36:24 2014
  5. all end: Fri Apr 25 10:36:29 2014

发表评论

表情:
评论列表 (有 0 条评论,34人围观)

还没有评论,来说两句吧...

相关阅读