python 多线程 入门
2016-06-03 12:58
357 查看
python里的多线程,一直用得不是很多。为了最快速的上手,搞明白多线程到底是个什么鬼,写了个简单的例子
代码运行结果
对代码做个简单的分析:
首先创建一个空的threads列表,用来存放线程。然后分别创建线程thread_music与thread_moive。
将Thread中源码构造函数的说明部分抠出来:
通过源码,很容易看出来
是如何构造一个线程的。
jion()方法放在for循环外边,就是说必须要等for循环里的两个进程都结束以后,才能继续执行主进程。
从代码最后的结果来分析,thread_music与thread_movie是同时开始执行的,music进程sleep1s后执行第二次,而movie进程sleep5s后执行第二次。主进程在两个线程都执行完了以后才执行。
#!/usr/bin/env python #coding:utf-8 ''' Created on 2016年6月3日 @author: lei.wang ''' import threading from time import ctime,sleep def music(entertainment): for i in range(2): print "Listening to %s. %s" %(entertainment,ctime()) sleep(1) def movie(entertainment): for i in range(2): print "Watching the %s. %s" %(entertainment,ctime()) sleep(5) if __name__ == '__main__': threads = [] thread_music = threading.Thread(target=music,args=(u"暗号",)) threads.append(thread_music) thread_movie = threading.Thread(target=movie,args=(u"肖圣克救赎",)) threads.append(thread_movie) for each in threads: each.setDaemon(True) each.start() each.join() print "all threads end at %s" %(ctime())
代码运行结果
Listening to 暗号. Fri Jun 3 12:38:12 2016 Watching the 肖圣克救赎. Fri Jun 3 12:38:12 2016 Listening to 暗号. Fri Jun 3 12:38:13 2016 Watching the 肖圣克救赎. Fri Jun 3 12:38:17 2016 all threads end at Fri Jun 3 12:38:22 2016
对代码做个简单的分析:
首先创建一个空的threads列表,用来存放线程。然后分别创建线程thread_music与thread_moive。
将Thread中源码构造函数的说明部分抠出来:
class Thread(_Verbose): """A class that represents a thread of control. This class can be safely subclassed in a limited fashion. """ __initialized = False # Need to store a reference to sys.exc_info for printing # out exceptions when a thread tries to use a global var. during interp. # shutdown and thus raises an exception about trying to perform some # operation on/with a NoneType __exc_info = _sys.exc_info # Keep sys.exc_clear too to clear the exception just before # allowing .join() to return. __exc_clear = _sys.exc_clear def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None): """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 a subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.__init__()) before doing anything else to the thread. """
通过源码,很容易看出来
thread_music = threading.Thread(target=music,args=(u"暗号",))
是如何构造一个线程的。
jion()方法放在for循环外边,就是说必须要等for循环里的两个进程都结束以后,才能继续执行主进程。
从代码最后的结果来分析,thread_music与thread_movie是同时开始执行的,music进程sleep1s后执行第二次,而movie进程sleep5s后执行第二次。主进程在两个线程都执行完了以后才执行。
相关文章推荐
- python challenge 13-16关 攻略
- 小强IT游记之新疆行
- python challenge 0-6关 攻略
- python把字典转换成json字符串
- python-module 'pymysql' has no attribute 'connect'
- 解决在Windows server 2008 安装Python2.7版本
- numpy常用函数
- Python configparser模块
- python urllib2
- python爬虫基础A
- python中的@符号的作用
- python 基本语法
- Python NLTK学习
- PYTHON 自定义异常类的使用
- Python的静态方法和类方法有什么区别
- Python 输出文字带颜色
- 命令形式新建第一个python 项目
- Python函数式练习
- 小强IT游记之大连行
- adaboost算法