- 線程狀態
新建,就緒,運行,阻塞,死亡。 - 線程同步
多線程可以同時運行多個任務,線程需要共享數據的時候,可能出現數據不同步的問題,用最習慣的LabVIEW來說,多線程中的2個循環如果一個對數組進行寫入,另一個進行讀取,就有可能導致還沒寫入就要讀取,為了避免這種情況,就要給線程加鎖。
鎖有兩種狀態-鎖定和未鎖定。每當一個線程要訪問共享數據的時候,必須先獲得鎖定,如果有別的線程已經獲得鎖定了,那么該線程就得暫停,這個稱之為同步阻塞。等到另外的線程訪問完畢之后,釋放鎖,該線程才能繼續訪問。 - 線程通信
另外一種可能就是數組還沒有創建,寫入線程和讀取線程肯定不能運行,所以必須等待創建線程的通知。所以引入了條件變量。
條件變量允許線程在條件不滿足的時候等待,條件滿足的時候開始運行。 - 線程運行和阻塞的狀態轉換
同步阻塞指處于競爭鎖定的狀態,線程請求鎖定時進入這個狀態,一旦成功獲得鎖定時又恢復到運行狀態。
等待阻塞是指等待其他線程通知的狀態,線程獲得條件鎖定后,調用等待將進入這個狀態,一旦其他線程發出通知,線程將進入同步阻塞狀態,再次競爭條件鎖定。
其他阻塞是指調用time.sleep(),anotherthread.join()或者等待IO時的阻塞,這個狀態下線程不會釋放已獲得的鎖定。 - thread模塊
import thread
import time
#在線程中執行的函數
def func():
for i in range(5):
print 'func'
time.sleep(1)
#結束當前線程
thread.exit()
#與thread.exit_thread()等價
#func返回的時候,線程同樣會結束
#啟動線程,線程立即開始運行
thread.start_new(func,())
#這個方法和thread.start_new_thread()等價
#第一個參數是方法,第二個參數是方法的參數,如果沒有參數,傳入空的元組
#創建鎖
lock = thread.allocate()
#這個方法和thread.allocate_lock()等價
#判斷鎖的狀態,鎖定還是釋放
print lock.locked()
#鎖通常用于控制對共享資源的訪問
count = 0
#獲得鎖,成功獲得鎖定后返回True
#可選的timeout參數不填將一直阻塞到獲得鎖定
#否則超時后返回False
if lock.acquire():
print "True"
count += 1
#釋放鎖
lock.release()
#thread模塊提供的線程都在主線程結束后同時結束
time.sleep(6)```
`thread.interrupt_main()`:在其他線程中終止主線程。
6. threading模塊
鎖Lock和條件變量Condition在Python中是獨立對象。
`threading.currentThread()`:返回當前的線程變量
`threading.enumerate()`:返回一個正在運行的線程的list,指線程啟動后,結束前。
`threading.activeCount()`:返回正在運行的線程數量,`len(threading.enumerate())`有相同的結果。
threading提供的類,Thread,Lock,Rlock,Condition,[Bounded]Semaphore,Event,Timer,local
1. Thread
import threading
開啟線程,將要執行的函數作為參數傳給Thread的構造方法
def func():
print "func() passed to Thread"
t = threading.Thread(target=func)
t.start()
從Thread繼承,重寫run(),在線程開始運行的時候就會運行run
class MyThread(threading.Thread):
def run(self):
print "MyThread extended from Thread"
t = MyThread()
t.start()```
isAlive()
:返回線程是否在運行。
get/setName(name)
:獲取/設置線程名
is/setDaemon(bool):
獲取/設置是否守護線程
start()
啟動線程
join([timeout])
:阻塞當前上下文的線程,直到調用此方法的線程終止或者到達指定的timeout
#join()的一個用法
import threading
import time
def context(tJoin):
print "in threadContext"
#啟動參數傳遞過來的線程
tJoin.start()
#阻塞tContext直到thread tJoin線程終止
tJoin.join()
#tJoin結束后繼續運行
print "out threadContext"
def joinfunc():
print "in threadJoin"
time.sleep(4)
print 'out threadJoin'
#創建線程tJoin,在tContext線程中運行,然后阻塞tContext
#tJoin運行完之后,繼續tContext線程
tjoin = threading.Thread(target=joinfunc)
tContext = threading.Thread(target=context,args=(tjoin,))
tContext.start()```
2. Lock
Lock指令鎖是可用的最低級的同步指令,Lock處于鎖定狀態時候,不被特定的線程擁有,Lock包含兩種狀態鎖定和非鎖定,以及兩個基本方法。
可以認為Lock又一個鎖定池,當線程請求鎖定時,將線程置于池中,直到獲得鎖定后出池。池中的線程處于同步阻塞的狀態。
acquire([timeout])使得線程進入同步阻塞狀態,嘗試獲得鎖定,也就是用在哪個線程,哪個線程就處于阻塞,直到獲得鎖定,獲得鎖定后需要釋放鎖
release()釋放鎖,使用前當前線程必須已經獲得鎖定
import threading
import time
data = 0
lock = threading.Lock()
def func():
global data
print "%s acquire lock..."% threading.currentThread().getName()
#調用acquire()時候,線程一直阻塞,直到獲得鎖定
#返回是否獲得鎖
if lock.acquire():
print "%s get the lock"% threading.currentThread().getName()
data += 1
time.sleep(2)
print "%s release lock..."%threading.currentThread().getName()
lock.release()
t1 = threading.Thread(target=func)
t2 = threading.Thread(target=func)
t3 = threading.Thread(target=func)
t1.start()
t2.start()
t3.start()```
終于弄懂了Lock()這塊,acquire(),release()的用法
- RLock
RLock可重入鎖是一個可以被同一個線程請求多次的同步指令,處于鎖定狀態時,RLock被某個線程擁有,擁有RLock的線程可以在此調用acquire(),釋放鎖的時候需要調用release()相同次數。
可以認為RLock包含一個鎖定池和一個初始值為0的計數器,每次成功調用acquire()/release(),計數器加一或者減一,為0的時候鎖處于未鎖定狀態。
import threading
import time
rlock = threading.RLock()
def func():
#第一次請求鎖定
print '%s acquire lock..'%threading.currentThread().getName()
if rlock.acquire():
print "%s get the lock"%threading.currentThread().getName()
time.sleep(2)
#第二次請求鎖定
print "%s acquire lock again.."%threading.currentThread().getName()
if rlock.acquire():
print "%s get the lock"%threading.currentThread().getName()
time.sleep(2)
#第一次釋放鎖
print "%s release lock "%threading.currentThread().getName()
rlock.release()
time.sleep(2)
#第二次釋放鎖
print "%s release lock "%threading.currentThread().getName()
rlock.release()
t1 = threading.Thread(target=func)
t2 = threading.Thread(target=func)
t3 = threading.Thread(target=func)
t1.start()
t2.start()
t3.start()```
4. Condition
Condition通常和一個鎖關聯,需要在多個Condition中共享一個鎖時,可以傳遞一個Lock/RLock實例給構造方法,否則它將自己生成一個RLock實例
除了Lock帶有的鎖定池外,Condition還包含一個等待池,池中的線程處于等待阻塞狀態,直到另一個線程調用notify()/notifyAll()通知,得到通知后線程進入鎖定池等待鎖定。
acquire()/release():調用關聯的鎖的相應方法
wait():調用這個方法將使線程進入Condition的等待池等待通知,并且釋放鎖。使用前線程必須已經獲得鎖定。
notify()調用這個方法將從等待池中挑選一個線程并且通知,收到通知的線程將自動調用acquire()嘗試獲得鎖定。其他線程仍然在等待池中,調用這個方法不回釋放鎖定,使用前線程已獲得鎖定。
notifyAll()調用這個方法將通知等待池中所有線程,這些線程都將進入鎖定池嘗試獲得鎖定,調用這個方法不會釋放鎖定,使用前必須已獲得鎖定。
這兩個方法都是用于已經獲得鎖定的線程。
import threading
import time
product = None
con = threading.Condition()
生產者方法
def produce():
global product
#該進程獲得鎖
if con.acquire():
while True:
if product is None:
print "produce..."
product = "anything"
#通知消費者,商品已經生產
con.notify()
#使得這個線程進入等待阻塞,并且釋放鎖
con.wait()
time.sleep(2)
消費者
def consume():
global product
#嘗試該線程加鎖
if con.acquire():
while True:
if product is not None:
print "consume..."
product = None
#通知
con.notify()
con.wait()
time.sleep(2)
t1 = threading.Thread(target=produce)
t2 = threading.Thread(target=consume)
t2.start()
t1.start()```
很有意思的小程序啊
- Semaphore/BoundedSemaphore
信號量,管理一個內置的計數器,每當調用acquire()時候-1,調用release()時候+1,計數器不能小于0.當計數器為0時候,acquire()將阻塞線程至同步鎖定狀態,直到其他線程調用release()
Semaphore經常來同步一些油訪客上限的對象,如連接池。
BoundedSemaphore與Semaphore的唯一區別是前者將在調用release()時候檢查計數器的值是否超過了計數器的初始值。
Semaphore(value=1):value是計數器的初始值。
acquire()請求Semaphore,如果計數器為0,將阻塞線程至同步阻塞狀態,否則將計數器-1并立即返回
release()釋放Semaphore,將計數器+1,如果使用BoundedSemaphore,還將進行釋放次數檢查,release()方法不檢查線程是否已經獲得Semaphore
import threading
import time
semaphore = threading.BoundedSemaphore(2)
def func():
#請求Semaphore,成功后計數器-1,計數器為0的時候阻塞
print "%s acquire semaphore..."%threading.currentThread().getName()
if semaphore.acquire():
print "%s get semaphore"%threading.currentThread().getName()
time.sleep(4)
#釋放Semaphore,計數器+1
print '%s release semaphore'%threading.currentThread().getName()
semaphore.release()
t1 = threading.Thread(target=func)
t2 = threading.Thread(target=func)
t3 = threading.Thread(target=func)
t4 = threading.Thread(target=func)
t1.start()
t2.start()
t3.start()
t4.start()
time.sleep(2)
#沒有獲得semaphore的主線程也可以調用release
#如果使用BoundedSemaphore,主線程釋放后將拋出異常
print "mainthread release semaphore without acquire"
semaphore.release()```
想起了復習操作系統時候的信號量啊!
6. Event
Event是最簡單的線程通信機制,一個線程通知事件,其他線程等待事件,Event內置了一個初始為False的標志,當調用set()時設為True,調用clear()時重置為False,wait()將阻塞線程至等待阻塞狀態。
Event沒有鎖,無法使線程進入同步阻塞狀態。
isSet()當內置標志為True時候返回True
set()將標志設為True,并且通知所有處于等待阻塞狀態的線程恢復運行狀態。
clear()將標志設為False
wait()如果標志為True則立即返回,否則阻塞線程至等待阻塞狀態,等待其他線程調用set()
import threading
import time
event = threading.Event()
def func():
#等待事件,進入等待阻塞狀態
print "%s wait for event"%threading.currentThread().getName()
#如果標志為True立即返回,否則阻塞線程至等待阻塞狀態,等待其他線程調用set()
event.wait()
#收到事件后進入運行狀態
print "%s recv event"%threading.currentThread().getName()
t1 = threading.Thread(target=func)
t2 = threading.Thread(target=func)
t1.start()
t2.start()
time.sleep(2)
發送事件通知
print "mainthread set event"
將標志設為True,通知所有處于等待阻塞狀態的線程恢復運行狀態
event.set()```
- Timer
Timer定時器是Thread的派生類,用于在指定時間后調用一個方法
Timer(interval,function,args,kwargs)
interval指定的時間,function要執行的方法
import threading
def func():
print "hello timer!"
timer = threading.Timer(5,func)
timer.start()```
8. local
local是一個小寫字母開頭的類,用于管理線程局部的數據,對于同一個local,線程無法訪問其他線程設置的屬性,線程設置的屬性不會被其他線程設置的同名屬性替換。
可以把local看成一個線程屬性字典的字典,local封裝了從自身使用線程作為key檢索對應的屬性字典,再使用屬性名作為key檢索屬性值的細節。
import threading
local = threading.local()
local.tname = 'main'
def func():
local.tname = 'not main'
print local.tname
t1 = threading.Thread(target=func)
t1.start()
阻塞主線程,直到t1線程運行完畢
t1.join()
print local.tname```
一個例子
import threading
alist = None
condition = threading.Condition()
def doSet():
global alist
print "%s acquire lock"%threading.currentThread().getName()
if condition.acquire():
print '%s get lock'%threading.currentThread().getName()
while alist is None:
condition.wait()
print "%s wait notify"%threading.currentThread().getName()
print "%s get notify"%threading.currentThread().getName()
for i in range(len(alist))[::-1]:
alist[i] = i
print "%s release lock"%threading.currentThread().getName()
condition.release()
def doPrint():
global alist
if condition.acquire():
while alist is None:
condition.wait()
for i in alist:
print i,
print
condition.release()
def doCreate():
global alist
if condition.acquire():
if alist is None:
alist = [i for i in range(10)]
condition.notifyAll()
condition.release()
tset = threading.Thread(target=doSet,name='tset')
tprint = threading.Thread(target=doPrint,name='tprint')
tcreate = threading.Thread(target=doCreate,name='tcreate')
tset.start()
tprint.start()
tcreate.start()```