threading通過對thread模塊進行二次封裝,提供了更方便的API來操作線程。本文對threading常用部分進行介紹。
創建線程
1.通過繼承Thread類,重寫它的run方法
#-*-coding:utf-8 -*-
#!usr/bin/envpython
import threading, time, random
count = 0
class 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/envpython
import threading, time, random
count = 0
lock =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, time
def 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