python多執行緒程式設計 4 死鎖和可重入鎖

2021-09-08 23:48:19 字數 2925 閱讀 1721

#

encoding: utf-8

import threading

import time

class mythread(threading.thread):

def do1(self):

global resa, resb

if mutexa.acquire():

msg = self.name+'

got resa

'print msg

if mutexb.acquire(1):

msg = self.name+'

got resb

'print msg

mutexb.release()

mutexa.release()

def do2(self):

global resa, resb

if mutexb.acquire():

msg = self.name+'

got resb

'print msg

if mutexa.acquire(1):

msg = self.name+'

got resa

'print msg

mutexa.release()

mutexb.release()

def run(self):

self.do1()

self.do2()

resa = 0

resb = 0

mutexa = threading.lock()

mutexb = threading.lock()

def test():

for i in range(5):

t = mythread()

t.start()

if__name__ == '

__main__

':test()

執行結果:

thread-1 got resa

thread-1 got resb

thread-1 got resb

thread-1 got resa

thread-2 got resa

thread-2 got resb

thread-2 got resb

thread-2 got resa

thread-3 got resa

thread-3 got resb

thread-3 got resb

thread-3 got resa

thread-5 got resa

thread-5 got resb

thread-5 got resb

thread-4 got resa

此時程序已經死掉。

更簡單的死鎖情況是乙個執行緒「迭代」請求同乙個資源,直接就會造成死鎖:

import threading

import time

class mythread(threading.thread):

def run(self):

global num

time.sleep(1)

if mutex.acquire(1):

num = num+1

msg = self.name+'

set num to

'+str(num)

print msg

mutex.acquire()

mutex.release()

mutex.release()

num = 0

mutex = threading.lock()

def test():

for i in range(5):

t = mythread()

t.start()

if__name__ == '

__main__

':test()

為了支援在同一執行緒中多次請求同一資源,python提供了「可重入鎖」:threading.rlock。rlock內部維護著乙個lock和乙個counter變數,counter記錄了acquire的次數,從而使得資源可以被多次require。直到乙個執行緒所有的acquire都被release,其他的執行緒才能獲得資源。上面的例子如果使用rlock代替lock,則不會發生死鎖:

import threading

import time

class mythread(threading.thread):

def run(self):

global num

time.sleep(1)

if mutex.acquire(1):

num = num+1

msg = self.name+'

set num to

'+str(num)

print msg

mutex.acquire()

mutex.release()

mutex.release()

num = 0

mutex = threading.rlock()

def test():

for i in range(5):

t = mythread()

t.start()

if__name__ == '

__main__

':test()

執行結果:

thread-1 set num to 1

thread-3 set num to 2

thread-2 set num to 3

thread-5 set num to 4

thread-4 set num to 5

Python 多執行緒4 死鎖

encoding utf 8 import threading import time class mythread threading.thread def do1 self global resa,resb if mutexa.acquire msg self.name got resa pri...

python 多執行緒 互斥鎖和死鎖

在上一節提到的資源搶占的問題,那麼這個問題如何解決呢?互斥鎖就可以解決這個問題 資源搶占的問題原因在於兩個執行緒操作同乙個資源,此時這個資源的內容就混亂了,對於兩個執行緒都不能正常服務 此時就可以考慮在乙個執行緒工作的時候,將執行緒鎖定,其他執行緒無法訪問,這就是互斥鎖 當多個執行緒幾乎同時修改某乙...

多執行緒程式設計之執行緒死鎖問題

在多執行緒程式設計中,除了要解決資料訪問的同步與互斥之外,還需要解決的重要問題就是多執行緒的死鎖問題。所謂死鎖 是指兩個或兩個以上的程序 執行緒 在執行過程中,因爭奪資源而造成的一種互相等待的現象,若無外部處理作用,它們都將無限等待下去。一 死鎖原因與形成條件 死鎖形成的原因 系統資源不足 程序 執...