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