pthon 執行緒之死鎖

2021-08-19 15:46:03 字數 2275 閱讀 4710

這個是我們應該要避免出現的情況。

# !/usr/bin/python

# -*- coding:utf-8 -*-

# ++++++++++++++++++++

# author: fmspider

# time: 2018-5-3 11:35

# function: 死鎖現象

import threading, time

class mythread(threading.thread):

def a(self):

locka.acquire()

print(self.name, 'gotlocka', time.ctime())

time.sleep(3)

lockb.acquire()

print(self.name, 'gotlockb', time.ctime())

lockb.release()

locka.release()

def b(self):

lockb.acquire()

print(self.name, 'gotlockb', time.ctime())

time.sleep(2)

locka.acquire()

print(self.name, 'gotlocka', time.ctime())

locka.release()

lockb.release()

def run(self):

self.a()

self.b()

if __name__ == '__main__':

locka = threading.lock()

lockb = threading.lock()

threads =

for i in range(5):

for t in threads:

t.start()

for t in threads:

t.join() # 等待純種結果。

執行結果:程式陷入死迴圈

解決方法:

# !/usr/bin/python

# -*- coding:utf-8 -*-

# ++++++++++++++++++++

# author: fmspider

# time: 2018-5-3 11:35

# function: 死鎖現象

import threading, time

class mythread(threading.thread):

def a(self):

lock.acquire()

print(self.name, 'gotlocka', time.ctime())

time.sleep(3)

lock.acquire()

print(self.name, 'gotlockb', time.ctime())

lock.release()

lock.release()

def b(self):

lock.acquire()

print(self.name, 'gotlockb', time.ctime())

time.sleep(2)

lock.acquire()

print(self.name, 'gotlocka', time.ctime())

lock.release()

lock.release()

def run(self):

self.a()

self.b()

if __name__ == '__main__':

# locka = threading.lock()

# lockb = threading.lock()

lock = threading.rlock()

threads =

for i in range(5):

for t in threads:

t.start()

for t in threads:

t.join() # 等待純種結果。

執行結果:

多執行緒之死鎖

1 死鎖發生的場景 有時候兩個或者多個執行緒需要訪問同乙份資源,這裡就涉及到執行緒同步的問題 thread1 synchronized object1 thread2 synchronized object2 看看上面的例子,兩個執行緒各自都有想要訪問對方的想法,可是雙方都不願意放手,就像a拿到了開...

多執行緒之死鎖

死鎖。同步中巢狀同步。你有一根筷子,我有一根筷子,我要吃飯,你不給我,我不給你,誰都吃不著飯,死鎖發生,但是死鎖不一會發生,也會存在和諧的狀態,就是你把筷子給我,我吃一口,我再把筷子給你,你再吃一口 class ticket implements runnable else while true s...

java多執行緒之 死鎖

當兩個或多個執行緒競爭試圖獲取對方持有的同步鎖時,它們都會處於阻塞狀態,除非某個執行緒主動釋放自己所持有的同步鎖,這時,死鎖就出現了。用下面這張圖很好理解 如圖,執行緒thread1和thread2都有兩個同步方法operation1 operation2 operation1 中會呼叫operat...