其他分享
首页 > 其他分享> > 线程死锁跟解决

线程死锁跟解决

作者:互联网

因为多线程同时操作同一个变量时,可能会出现资源竞争的情况,导致程序结果不对

此时需要对被操作的全局变量上锁,上锁后会得到正确结果

但是,如果线程A,拥有锁A, 线程B,拥有锁B,在锁A、锁B没释放的时候,线程B去获取锁A,线程A去获取锁B就会进入死锁

 

死锁示例:

#encoding='utf-8'
import threading
from time import sleep


mutexA = threading.Lock()
mutexB = threading.Lock()

def work1():
    mutexA.acquire()
    print('work1 get mutexA')
    sleep(1)
    mutexB.acquire()
    print('work1 get mutexB')
    print('work1 complete!')


def work2():
    mutexB.acquire()
    print('work2 get mutexB')
    sleep(1)
    mutexA.acquire()
    print('work2 get mutexA')
    print('work2 complete!')


def main():
    t1 = threading.Thread(target=work1)
    t2 = threading.Thread(target=work2)
    t1.start()
    t2.start()


if __name__ == '__main__':
    main()
View Code

 

标签:threading,print,死锁,线程,mutexB,解决,work1,work2,mutexA
来源: https://www.cnblogs.com/lurenjia1994/p/10394565.html