Py004-01-13互斥锁

互斥锁

多线程下操作同一数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import time
from threading import Thread

n = 100

def task():
global n
temp = n
time.sleep(0.1)
n = temp-1

if __name__ == '__main__':
arr = []
for i in range(100):
t = Thread(target=task)
arr.append(t)
t.start()

# 保证所有线程都执行完毕
for t in arr:
t.join()

print('主',n)

执行结果:
主 99

此时就不安全了,100个线程都操作了但是数据还是99

互斥锁的应用

牺牲效率来保证数据的安全——将并行变成串行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import time
from threading import Thread,Lock

n = 100

def task(mutex):
global n
mutex.acquire()
temp = n
time.sleep(0.1)
n = temp-1
mutex.release()

if __name__ == '__main__':
mutex=Lock()
arr = []
for i in range(100):
t = Thread(target=task,args=(mutex,))
arr.append(t)
t.start()

# 保证所有线程都执行完毕
for t in arr:
t.join()

print('主',n)