多线程--互斥锁之死锁的演示实例 及死锁的解决方法 添加超时时间

线程

线程可以简单理解为同一进程中有多个计数器,每个线程的执行时间不确定,而每个进程的时间片相等,线程是操作系统调度执行的最小单位。

死锁

在线程间共享多个资源的时候,如果两个线程分别占有一部分资源并且同时等待对方的资源,就会造成死锁,尽管死锁很少发生,但一旦发生就会造成应用的停止响应。

死锁的演示

死锁实例:

import threading
import time

#创建互斥锁,默认是没有上锁时
mutex_1 = threading.Lock()
mutex_2 = threading.Lock()

def test1():
    print("in test1 lock 1")
    mutex_1.acquire()
    time.sleep(3)
    mutex_2.acquire()
    print("in test1 step lock 2")
    mutex_1.release()

def test2():
    print("in test2 lock 2")
    mutex_2.acquire()
    time.sleep(3)
    mutex_1.acquire()
    print("in test2 step lock 1")
    mutex_1.release()
    mutex_2.release()

if __name__ == '__main__':
    t1 = threading.Thread(target=test1)
    t2 = threading.Thread(target=test2)
    t1.start()
    t2.start()

结果:

in test1 lock 1
in test2 lock 2

说明,test1与test2 相互锁定,不等继续进行。

添加超时时间

添加超时时间的方法就是在acquire()内添加timeout=,并设置超时时间
语法演示:

import threading
import time

# 创建互斥锁,默认是没有上锁时
mutex_1 = threading.Lock()
mutex_2 = threading.Lock()

def test1():
    print("in test1 lock 1")
    mutex_1.acquire()
    time.sleep(3)
    mutex_2.acquire(timeout=1)
    print("in test1 step lock 2")
    mutex_1.release()

def test2():
    print("in test2 lock 2")
    mutex_2.acquire()
    time.sleep(3)
    mutex_1.acquire()
    print("in test2 step lock 1")
    mutex_1.release()
    mutex_2.release()

if __name__ == '__main__':
    t1 = threading.Thread(target=test1)
    t2 = threading.Thread(target=test2)
    t1.start()
    t2.start()

结果:

in test1 lock 1
in test2 lock 2
in test1 step lock 2
in test2 step lock 1

说明,超时时间解决了test1与test2的 相互锁定,程序运行完毕。

猜你喜欢

转载自blog.csdn.net/weixin_44850984/article/details/89249363