1.互斥锁:
互斥锁:Lock 原理就是把并发变成串行,一个一个运行,不错乱,但效率低
保证多个进程修改一块数据时,大家是一个一个修改,不错乱
mutex.acquire()
mutex.release()
1 from multiprocessing import Process,Lock
2 import time
3
4 def task(name,mutex):
5 mutex.acquire()
6 print('%s 1'%name)
7 time.sleep(1)
8 print('%s 2'%name)
9 time.sleep(1)
10 print('%s 3'%name)
11 mutex.release()
12
13 if __name__ == "__main__":
14 # 这样写,子进程会copy一份,就变成了全新的锁 ,但是我们应该要让所有的进程持一把锁,
15 # 所以就把锁 传进去,共用一把锁
16 mutex = Lock()
17 for i in range(3):
18 p = Process(target=task,args=('进程%s'%i,mutex))
19 p.start()
20 """
21 # 大家共享资源,错乱了,这里共享终端,打印,结果3个进程错位打印了
22 进程1 1
23 进程2 1
24 进程0 1
25 进程2 2
26 进程0 2
27 进程1 2
28 进程1 3
29 进程0 3
30 进程2 3
31 """
32 """
33 # 执行效率低了,但是保证了不错乱
34 进程0 1
35 进程0 2
36 进程0 3
37 进程2 1
38 进程2 2
39 进程2 3
40 进程1 1
41 进程1 2
42 进程1 3
43 """
2.模拟抢票:
多个进程操作同一个文件时,需要上互斥锁:eg:抢票往文件里的票数-1,否则有问题,多人都抢到票,但只有一张
mutex.acquire()
mutex.release()
1 import json
2 import time
3 from multiprocessing import Process,Lock
4
5
6 def search(name):
7 time.sleep(1)
8 dic = json.load(open('db.txt', 'r', encoding='utf-8'))
9 print('<%s> 查看剩余票数【%s】'%(name,dic['count']))
10
11 def get(name):
12 time.sleep(1)
13 dic = json.load(open('db.txt', 'r', encoding='utf-8'))
14 if dic['count'] > 0:
15 dic['count'] -= 1
16 time.sleep(3)
17 json.dump(dic,open('db.txt','w',encoding='utf-8'))
18 print('<%s> 购票成功'%name)
19
20 def task(name,mutex):
21 search(name)
22 mutex.acquire() # 加上互斥锁 之后,就可以只有一个人购票成功了
23 get(name)
24 mutex.release()
25
26 if __name__ == "__main__":
27 mutex = Lock()
28 for i in range(10):
29 p = Process(target=task,args=('路人%s'%i,mutex))
30 p.start()
3.互斥锁与join区别:
join:是把代码整体变成了串行
互斥锁:可以把局部的代码变成串行,只对“共享数据修改”那里上锁
1 import json
2 import time
3 from multiprocessing import Process,Lock
4
5
6 def search(name):
7 time.sleep(1)
8 dic = json.load(open('db.txt', 'r', encoding='utf-8'))
9 print('<%s> 查看剩余票数【%s】'%(name,dic['count']))
10
11 def get(name):
12 time.sleep(1)
13 dic = json.load(open('db.txt', 'r', encoding='utf-8'))
14 if dic['count'] > 0:
15 dic['count'] -= 1
16 time.sleep(3)
17 json.dump(dic,open('db.txt','w',encoding='utf-8'))
18 print('<%s> 购票成功'%name)
19
20 def task(name):
21 search(name)
22 # mutex.acquire() # 加上互斥锁 之后,就可以只有一个人购票成功了
23 get(name)
24 # mutex.release()
25
26 if __name__ == "__main__":
27 mutex = Lock()
28 for i in range(10):
29 p = Process(target=task,args=('路人%s'%i,))
30 p.start()
31 p.join()