您的位置:首页 > 编程语言 > Python开发

python 多线程 入门

2016-06-03 12:58 357 查看
python里的多线程,一直用得不是很多。为了最快速的上手,搞明白多线程到底是个什么鬼,写了个简单的例子

#!/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后执行第二次。主进程在两个线程都执行完了以后才执行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: