锁
1.互斥锁的使用
import threading
#创建
lockname=threading.acquire
# 上锁
lockname.lock()
#解锁
lockname.release()
详细使用(例子)
import threading
from threading import Thread
global_number = 0
def sum_num1():
# 上锁
mutex.acquire()
for i in range(1000000):
# 调用global函数实现在函数内部修改全局变量
global global_number
global_number += 1
# 解锁
mutex.release()
print(f'global_number:{global_number}')
def sum_num2():
# 上锁
mutex.acquire()
for i in range(1000000):
global global_number
global_number += 1
# 解锁
mutex.release()
print(f'global_numbe2:{global_number}')
if __name__ == '__main__':
# 创建锁
mutex=threading.Lock()
t1 = Thread(target=sum_num1)
t2 = Thread(target=sum_num2)
t1.start()
t2.start()
t1.join()
t2.join()
print('Main Thread End.')
# global_number:1000000
# global_numbe2:2000000
# Main Thread End.
# 想了解不加锁的情况运行的代码是什么样的只需要注释掉上锁和解锁的代码
2.死锁
import threading
from threading import Thread
global_number = 0
def sum_num1():
print('sum_num1....')
# 上锁
mutex.acquire()
for i in range(1000000):
# 调用global函数实现在函数内部修改全局变量
global global_number
global_number += 1
# 这里为了还原死锁状况我们不让解锁
print(f'global_number:{global_number}')
def sum_num2():
print('sum_num2....')
# 上锁
mutex.acquire()
for i in range(1000000):
global global_number
global_number += 1
# 不解锁
print(f'global_numbe2:{global_number}')
if __name__ == '__main__':
# 创建锁
mutex=threading.Lock()
t1 = Thread(target=sum_num1)
t2 = Thread(target=sum_num2)
t1.start()
t2.start()
t1.join()
t2.join()
print('Main Thread End.')
# sum_num1....
# sum_num2....
# global_number:1000000
# 产生死锁,无法继续执行代码,这要求我们在写多线程执行多任务时一定要养成好习惯,及时解锁