python多线程-threading模块

来源:互联网 发布:中兴u960s软件下载 编辑:程序博客网 时间:2024/05/17 23:26

threading通过对thread模块进行二次封装,提供了更方便的API来操作线程。本文对threading常用部分进行介绍。

 

创建线程

1.通过继承Thread类,重写它的run方法

#-*-coding:utf-8 -*-#!usr/bin/envpythonimport threading, time, randomcount = 0class Counter(threading.Thread):    def __init__(self, lock, threadName):        '''@summary: 初始化对象。               @param lock: 锁对象。        @param threadName: 线程名称。        '''        super(Counter, self).__init__(name =threadName)  #注意:一定要显式的调用父类的初始化函数。        self.lock = lock       def run(self):        '''@summary: 重写父类run方法,在线程启动后执行该方法内的代码。        '''        global count        self.lock.acquire()        for i in xrange(10000):            count = count + 1        self.lock.release()lock =threading.Lock()for i in range(5):    Counter(lock, "thread-" +str(i)).start()time.sleep(2)   #确保线程都执行完毕print count

2.创建一个threading.Thread对象,在它的初始化函数(__init__)中将可调用对象作为参数传入

#-*-coding:utf-8 -*-#!usr/bin/envpythonimport threading, time, randomcount = 0lock =threading.Lock()def doAdd():    '''@summary: 将全局变量count 逐一的增加10000。    '''    global count, lock    lock.acquire()    for i in xrange(10000):        count = count + 1    lock.release()for i inrange(5):    threading.Thread(target = doAdd, args = (),name = 'thread-' + str(i)).start()time.sleep(2)   #确保线程都执行完毕print count

threading.Lock()

锁对象。一个锁对象常用的方法为acquire()、release()。为防止不同线程修改数据造成不一致,通常需要使用到锁,加锁的代码段可以看做是单线程运行的,所以不会造成数据不一致。

 

Thread.name

获取线程的名称。

 

Thread.ident

获取线程的标识符。线程标识符是一个非零整数,只有在调用了start()方法之后该属性才有效,否则它只返回None。

 

Thread.join([timeout])

调用Thread.join将会使调用该线程的线程堵塞,直到被调用线程运行结束或超时,调用线程才可以继续执行。参数timeout是一个数值类型,表示超时时间,如果未提供该参数,那么主调线程将一直堵塞到被调线程结束。下面举个例子说明join()的使用:

import threading, timedef doWaiting():    print 'start waiting:',time.strftime('%H:%M:%S')    time.sleep(3)    print 'stop waiting',time.strftime('%H:%M:%S')thread1 =threading.Thread(target = doWaiting)thread1.start()time.sleep(1)  #确保线程thread1已经启动print 'startjoin'thread1.join()  #主线程将一直堵塞,直到thread1运行结束。print 'end join'

threading.current_thread()

获取当前的线程,返回Thread对象

 

Thread.getName()

获取线程的名称

 

Thread.setName()

设置线程的名称

 

Thread.is_alive()/Thread.isAlive()

判断线程是否是激活的(alive)。从调用start()方法启动线程,到run()方法执行完毕或遇到未处理异常而中断,这段时间内,线程是激活的。


参考资料:
1.http://python.jobbole.com/81546/
2.python核心编程第二版 chapter18
0 0
原创粉丝点击