互斥锁
互斥锁
互斥锁:对共享数据进行锁定,保证同一时刻只有一个线程去操作
注意:互斥锁是多个线程一起抢。抢到锁的线程先执行
互斥锁的使用
- 互斥锁的创建:
mutex = threading.Lock()
- 上锁:
mutex.acquire()
- 释放锁:
mutex.release()
# 全局变量
import threading
import time
g_num = 0
# 对g_num进行加操作
def sum_num1():
# 上锁
mutex.acquire()
for i in range(1000000):
global g_num
g_num += 1
# 解锁
mutex.release()
print(f'g_num1: {g_num}')
# 对g_num进行加操作
def sum_num2():
# 上锁
mutex.acquire()
for i in range(1000000):
global g_num
g_num += 1
# 解锁
mutex.release()
print(f'g_num2: {g_num}')
if __name__ == '__main__':
# 创建锁
mutex = threading.Lock()
# 创建子线程
sum1_thread = threading.Thread(target=sum_num1())
sum2_thread = threading.Thread(target=sum_num2())
# 启动线程
sum1_thread.start()
time.sleep(1)
sum2_thread.start()