标签:load count multi def 读数 arc 进程 for 进程同步
练习1、模拟抢车票(进程同步 锁)
代码1:(并发运行,效率高,但竞争同一文件,数据写入错乱)
from multiprocessing import Process
import time,json,random
def search():
dic=json.load(open(‘db.txt‘))
print(‘剩余票数%s‘ %dic[‘count‘])
def get():
dic=json.load(open(‘db.txt‘))
time.sleep(0.1) #模拟读数据的网络延迟
if dic[‘count‘] >0:
dic[‘count‘]-=1
time.sleep(0.2) #模拟写数据的网络延迟
json.dump(dic,open(‘db.txt‘,‘w‘))
print(‘购票成功‘)
def task():
search()
get()
for i in range(3): #模拟并发100个客户端抢票
p=Process(target=task)
p.start()
代码2:加锁:由并发变成了串行,牺牲了运行效率,但保证了数据的安全
from multiprocessing import Process,Lock
import json,time
def search():
dic=json.load(open(‘db.txt‘))
print(‘剩余票数%s‘ %dic[‘count‘])
def get():
dic = json.load(open(‘db.txt‘))
time.sleep(0.1)
if dic[‘count‘]>0:
dic[‘count‘]-=1
time.sleep(0.1)
json.dump(dic,open(‘db.txt‘,‘w‘))
print(‘购票成功‘)
else:
print(‘没票了‘)
def task(lock):
search()
lock.acquire()
get()
lock.release()
lock=Lock()
for i in range(3):
p=Process(target=task,args=(lock,))
p.start()
标签:load count multi def 读数 arc 进程 for 进程同步
原文地址:http://blog.51cto.com/10630401/2069958