(转)有关thread线程

Python 标准库提供了 thread 和 threading 两个模块来对多线程进行支持。其中, thread 模块以低级、原始的方式来处理和控制线程,而 threading 模块经过对 thread 进行二次封装,提供了更方便的 api 来处理线程。 虽然使用 thread 没有 threading 来的方便,但它更灵活。python

 

先看一段代码:api

 1 #coding=gbk
 2 import thread, time, random
 3 count = 0
 4 def threadTest():
 5     global count
 6     for i in xrange(10000):
 7         count += 1
 8 for i in range(10):
 9     thread.start_new_thread(threadTest, ())    #若是对start_new_thread函数不是很了解,不要着急,立刻就会讲解
10 time.sleep(3)
11 print count    #count是多少呢?是10000 * 10 吗?

 

thread.start_new_thread function args [ , kwargs ] )

函数将建立一个新的线程,并返回该线程的标识符(标识符为整数)。参数 function 表示线程建立以后,当即执行的函数,参数 args 是该函数的参数,它是一个元组类型;第二个参数 kwargs 是可选的,它为函数提供了命名参数字典。函数执行完毕以后,线程将自动退出。若是函数在执行过程当中遇到未处理的异常,该线程将退出,但不会影响其余线程的执行。 多线程

一个简单的例子:并发

#coding=gbk
import thread, time
def threadFunc(a = None, b = None, c = None, d = None):
    print time.strftime('%H:%M:%S', time.localtime()), a
    time.sleep(1)    
    print time.strftime('%H:%M:%S', time.localtime()), b
    time.sleep(1)
    print time.strftime('%H:%M:%S', time.localtime()), c
    time.sleep(1)
    print time.strftime('%H:%M:%S', time.localtime()), d
    time.sleep(1)
    print time.strftime('%H:%M:%S', time.localtime()), 'over'
 
thread.start_new_thread(threadFunc, (3, 4, 5, 6))    #建立线程,并执行threadFunc函数。
time.sleep(5)

thread.exit ()

结束当前线程。调用该函数会触发 SystemExit 异常,若是没有处理该异常,线程将结束。dom

thread.get_ident ()

返回当前线程的标识符,标识符是一个非零整数。ide

thread.interrupt_main ()

在主线程中触发 KeyboardInterrupt 异常。子线程可使用该方法来中断主线程。下面的例子演示了在子线程中调用 interrupt_main ,在主线程中捕获异常 :函数

import thread, time
thread.start_new_thread(lambda : (thread.interrupt_main(), ), ())
try:
    time.sleep(2)
except KeyboardInterrupt, e:
    print 'error:', e
print 'over'

下面介绍 thread 模块中的琐,琐能够保证在任什么时候刻,最多只有一个线程能够访问共享资源。ui

thread.LockType 是 thread 模块中定义的琐类型。它有以下方法:spa

lock.acquire ( [ waitflag ] )

获取琐。函数返回一个布尔值,若是获取成功,返回 True ,不然返回 False 。参数 waitflag 的默认值是一个非零整数,表示若是琐已经被其余线程占用,那么当前线程将一直等待,只到其余线程释放,而后获取访琐。若是将参数 waitflag 置为 0 ,那么当前线程会尝试获取琐,无论琐是否被其余线程占用,当前线程都不会等待。线程

lock.release ()

释放所占用的琐。

lock.locked ()

判断琐是否被占用。

如今咱们回过头来看文章开始处给出的那段代码:代码中定义了一个函数 threadTest ,它将全局变量逐一的增长 10000 ,而后在主线程中开启了 10 个子线程来调用 threadTest 函数。但结果并非预料中的 10000 * 10 ,缘由主要是对 count 的并发操做引来的。全局变量 count 是共享资源,对它的操做应该串行的进行。下面对那段代码进行修改,在对 count 操做的时候,进行加琐处理。看看程序运行的结果是否和预期一致。修改后的代码:

#coding=gbk
import thread, time, random
count = 0
lock = thread.allocate_lock() #建立一个琐对象
def threadTest():
    global count, lock
    lock.acquire() #获取琐

    for i in xrange(10000):
        count += 1

    lock.release() #释放琐
for i in xrange(10):
    thread.start_new_thread(threadTest, ())
time.sleep(3)
print count

 

threading.Thread

threading经过对thread模块进行二次封装,提供了更方便的API来操做线程。

Thread 是threading模块中最重要的类之一,可使用它来建立线程。有两种方式来建立线程:一种是经过继承Thread类,重写它的run方法;另外一种是建立一个threading.Thread对象,在它的初始化函数(__init__)中将可调用对象做为参数传入。下面分别举例说明。先来看看经过继承threading.Thread类来建立线程的例子:

 1 #coding=gbk
 2 import threading, time, random
 3 count = 0
 4 class Counter(threading.Thread):
 5     def __init__(self, lock, threadName):
 6         '''@summary: 初始化对象。
 7         
 8         @param lock: 琐对象。
 9         @param threadName: 线程名称。
10         '''
11         super(Counter, self).__init__(name = threadName)  #注意:必定要显式的调用父类的初始
12 化函数。
13         self.lock = lock
14     
15     def run(self):
16         '''@summary: 重写父类run方法,在线程启动后执行该方法内的代码。
17         '''
18         global count
19         self.lock.acquire()
20         for i in xrange(10000):
21             count = count + 1
22         self.lock.release()
23 lock = threading.Lock()
24 for i in range(5): 
25     Counter(lock, "thread-" + str(i)).start()
26 time.sleep(2)    #确保线程都执行完毕
27 print count

 

在代码中,咱们建立了一个Counter类,它继承了threading.Thread。初始化函数接收两个参数,一个是琐对象,另外一个是线程的名称。在Counter中,重写了从父类继承的run方法,run方法将一个全局变量逐一的增长10000。在接下来的代码中,建立了五个Counter对象,分别调用其start方法。最后打印结果。这里要说明一下run方法 和start方法: 它们都是从Thread继承而来的,run()方法将在线程开启后执行,能够把相关的逻辑写到run方法中(一般把run方法称为活动[Activity]。);start()方法用于启动线程。

 

再看看另一种建立线程的方法:

 1 import threading, time, random
 2 count = 0
 3 lock = threading.Lock()
 4 def doAdd():
 5     '''@summary: 将全局变量count 逐一的增长10000。
 6     '''
 7     global count, lock
 8     lock.acquire()
 9     for i in xrange(10000):
10         count = count + 1
11     lock.release()
12 for i in range(5):
13     threading.Thread(target = doAdd, args = (), name = 'thread-' + str(i)).start()
14 time.sleep(2)    #确保线程都执行完毕
15 print count

在这段代码中,咱们定义了方法doAdd,它将全局变量count 逐一的增长10000。而后建立了5个Thread对象,把函数对象doAdd 做为参数传给它的初始化函数,再调用Thread对象的start方法,线程启动后将执行doAdd函数。这里有必要介绍一下threading.Thread类的初始化函数原型:

def __init__(self, group=None, target=None, name=None, args=(), kwargs={})

  •   参数group是预留的,用于未来扩展;
  •   参数target是一个可调用对象(也称为活动[activity]),在线程启动后执行;
  •   参数name是线程的名字。默认值为“Thread-N“,N是一个数字。
  •   参数args和kwargs分别表示调用target时的参数列表和关键字参数。

Thread类还定义了如下经常使用方法与属性:

Thread.getName()

Thread.setName()

Thread.name

用于获取和设置线程的名称。

Thread.ident

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

Thread.is_alive()

Thread.isAlive()

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

Thread.join([timeout])

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

 1 import threading, time
 2 def doWaiting():
 3     print 'start waiting:', time.strftime('%H:%M:%S')
 4     time.sleep(3)
 5     print 'stop waiting', time.strftime('%H:%M:%S')
 6 thread1 = threading.Thread(target = doWaiting)
 7 thread1.start()
 8 time.sleep(1)  #确保线程thread1已经启动
 9 print 'start join'
10 thread1.join()    #将一直堵塞,直到thread1运行结束。
11 print 'end join'

threading.RLock和threading.Lock

在threading模块中,定义两种类型的琐:threading.Lock和threading.RLock。它们之间有一点细微的区别,经过比较下面两段代码来讲明:

1 import threading
2 lock = threading.Lock()    #Lock对象
3 lock.acquire()
4 lock.acquire()  #产生了死琐。
5 lock.release()
6 lock.release()
1 import threading
2 rLock = threading.RLock()  #RLock对象
3 rLock.acquire()
4 rLock.acquire()    #在同一线程内,程序不会堵塞。
5 rLock.release()
6 rLock.release()

这两种琐的主要区别是:RLock容许在同一线程中被屡次acquire。而Lock却不容许这种状况。注意:若是使用RLock,那么acquire和release必须成对出现,即调用了n次acquire,必须调用n次的release才能真正释放所占用的琐。

threading.Condition

能够把Condiftion理解为一把高级的琐,它提供了比Lock, RLock更高级的功能,容许咱们可以控制复杂的线程同步问题。threadiong.Condition在内部维护一个琐对象(默认是RLock),能够在建立Condigtion对象的时候把琐对象做为参数传入。Condition也提供了acquire, release方法,其含义与琐的acquire, release方法一致,其实它只是简单的调用内部琐对象的对应的方法而已。Condition还提供了以下方法(特别要注意:这些方法只有在占用琐(acquire)以后才能调用,不然将会报RuntimeError异常。):

Condition.wait([timeout]):

wait方法释放内部所占用的琐,同时线程被挂起,直至接收到通知被唤醒或超时(若是提供了timeout参数的话)。当线程被唤醒并从新占有琐的时候,程序才会继续执行下去。

Condition.notify():

唤醒一个挂起的线程(若是存在挂起的线程)。注意:notify()方法不会释放所占用的琐。

Condition.notify_all()

Condition.notifyAll()

唤醒全部挂起的线程(若是存在挂起的线程)。注意:这些方法不会释放所占用的琐。

 

threading.Event

Event实现与Condition相似的功能,不过比Condition简单一点。它经过维护内部的标识符来实现线程间的同步问题。(threading.Event和.NET中的System.Threading.ManualResetEvent类实现一样的功能。)

Event.wait([timeout])

堵塞线程,直到Event对象内部标识位被设为True或超时(若是提供了参数timeout)。

Event.set()

将标识位设为Ture

Event.clear()

将标识伴设为False。

Event.isSet()

判断标识位是否为Ture。

 

threading.Timer

threading.Timer是threading.Thread的子类,能够在指定时间间隔后执行某个操做。下面是Python手册上提供的一个例子:

1 def hello():
2     print "hello, world"
3 t = Timer(3, hello)
4 t.start() # 3秒钟以后执行hello函数。

threading模块中还有一些经常使用的方法没有介绍:

threading.active_count()
threading.activeCount()

获取当前活动的(alive)线程的个数。

threading.current_thread()
threading.currentThread()

获取当前的线程对象(Thread object)。

threading.enumerate()

获取当前全部活动线程的列表。

threading.settrace(func)

设置一个跟踪函数,用于在run()执行以前被调用。

threading.setprofile(func)

设置一个跟踪函数,用于在run()执行完毕以后调用。

相关文章
相关标签/搜索