Python-線程

  1. 線程狀態
    新建,就緒,運行,阻塞,死亡。
  2. 線程同步
    多線程可以同時運行多個任務,線程需要共享數據的時候,可能出現數據不同步的問題,用最習慣的LabVIEW來說,多線程中的2個循環如果一個對數組進行寫入,另一個進行讀取,就有可能導致還沒寫入就要讀取,為了避免這種情況,就要給線程加鎖。
    鎖有兩種狀態-鎖定和未鎖定。每當一個線程要訪問共享數據的時候,必須先獲得鎖定,如果有別的線程已經獲得鎖定了,那么該線程就得暫停,這個稱之為同步阻塞。等到另外的線程訪問完畢之后,釋放鎖,該線程才能繼續訪問。
  3. 線程通信
    另外一種可能就是數組還沒有創建,寫入線程和讀取線程肯定不能運行,所以必須等待創建線程的通知。所以引入了條件變量。
    條件變量允許線程在條件不滿足的時候等待,條件滿足的時候開始運行。
  4. 線程運行和阻塞的狀態轉換
    同步阻塞指處于競爭鎖定的狀態,線程請求鎖定時進入這個狀態,一旦成功獲得鎖定時又恢復到運行狀態。
    等待阻塞是指等待其他線程通知的狀態,線程獲得條件鎖定后,調用等待將進入這個狀態,一旦其他線程發出通知,線程將進入同步阻塞狀態,再次競爭條件鎖定。
    其他阻塞是指調用time.sleep(),anotherthread.join()或者等待IO時的阻塞,這個狀態下線程不會釋放已獲得的鎖定。
  5. 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()的用法

  1. 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()```
很有意思的小程序啊

  1. 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()```

  1. 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()```
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,119評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,382評論 3 415
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,038評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,853評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,616評論 6 408
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,112評論 1 323
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,192評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,355評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,869評論 1 334
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,727評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,928評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,467評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,165評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,570評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,813評論 1 282
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,585評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,892評論 2 372

推薦閱讀更多精彩內容

  • 多任務可以由多進程完成,也可以由一個進程內的多線程完成。我們前面提到了進程是由若干線程組成的,一個進程至少有一個線...
    壁花燒年閱讀 826評論 0 0
  • 線程 引言&動機 考慮一下這個場景,我們有10000條數據需要處理,處理每條數據需要花費1秒,但讀取數據只需要0....
    不浪漫的浪漫_ea03閱讀 370評論 0 0
  • 引言&動機 考慮一下這個場景,我們有10000條數據需要處理,處理每條數據需要花費1秒,但讀取數據只需要0.1秒,...
    chen_000閱讀 518評論 0 0
  • 線程 1.同步概念 1.多線程開發可能遇到的問題 同步不是一起的意思,是協同步調 假設兩個線程t1和t2都要對nu...
    TENG書閱讀 618評論 0 1
  • 前言 以下是本在學習javaSE階段的筆記和草稿,如有不足之處,望君指出我及時訂正。 接口:是代表集合的抽象數據類...
    封面人物小柚閱讀 581評論 0 0