Python提供了几个用于多线程编程的模块,包括thread, threading和Queue等。thread模块提供了基本的线程和锁的支持。threading模块提供了更高级别,功能更强的线程管理功能。Queue模块能够建立一个多个线程之间共享数据的队列。编程
下面介绍threading模块多线程
Thread 是threading模块中最重要的类之一,能够使用它来建立线程。有两种方式来建立线程:一种是经过继承Thread类,重写它的run方法;另外一种是建立一个threading.Thread对象,在它的初始化函数(__init__)中将可调用对象做为参数传入。下面分别举例说明。先来看看经过继承threading.Thread类来建立线程的例子:app
#create a thread with a function import threading from time import sleep, ctime loops = [4,2] def loop(nloop, nsec): print 'start loop', nloop, 'at:', ctime() sleep(nsec) print 'loop', nloop, 'done at:', ctime() def main(): print 'starting at:', ctime() threads=[] nloops = range(len(loops)) for i in nloops: #create the thread with the function, target= function name, args = function arguments t = threading.Thread(target=loop, args=(i, loops[i])) threads.append(t) for i in nloops: #start threads threads[i].start() for i in nloops: #wait for all threads[i].join() print 'all done at', ctime() if __name__ == '__main__': main()
这里要说明一下run方法 和start方法: 它们都是从Thread继承而来的,run()方法将在线程开启后执行,能够把相关的逻辑写到run方法中(一般把run方法称为活动[Activity]。);start()方法用于启动线程。ide
介绍一下threading.Thread类的初始化函数原型:函数
def __init__(self, group=None, target=None, name=None, args=(), kwargs={})oop
Thread类还定义了如下经常使用方法与属性:spa
用于获取和设置线程的名称。线程
获取线程的标识符。线程标识符是一个非零整数,只有在调用了start()方法以后该属性才有效,不然它只返回None。code
判断线程是不是激活的(alive)。从调用start()方法启动线程,到run()方法执行完毕或遇到未处理异常而中断 这段时间内,线程是激活的。对象
调用Thread.join将会使主调线程堵塞,直到被调用线程运行结束或超时。参数timeout是一个数值类型,表示超时时间,若是未提供该参数,那么主调线程将一直堵塞到被调线程结束