码迷,mamicode.com
首页 > 编程语言 > 详细

python_并发编程——锁

时间:2019-12-15 16:47:13      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:span   网络   start   elf   init   class   sleep   color   RoCE   

多进程模拟买票~

import time
import json
from multiprocessing import Process

class Show(Process):    #
    def run(self):
        with open(ticket) as f:
            dic = json.load(f)
            print("余票:{}".format(dic[ticket]))

class Buy_ticket(Process):  #
    def __init__(self,name):
        super().__init__()
        self.name = name
    def run(self):
        with open(ticket) as f:
            dic = json.load(f)
            time.sleep(0.1) #模拟网络延迟
        if dic[ticket] > 0:
            dic[ticket] -=1
            print({}买到票了~~~.format(self.name))
            time.sleep(0.1) #模拟网络延迟
            with open(ticket,w) as f:
                json.dump(dic,f)
        else:
            print({}没买到票!!!.format(self.name))
if __name__ == __main__:
    for i in range(10):
        q1 = Show()
        q1.start()
    for i in range(10):
        i = str(i)
        q2 = Buy_ticket(i)
        q2.start()

json文件:技术图片结果:技术图片余票为1却有两个人买到票了~。

加上锁之后

import time
import json
from multiprocessing import Process
from multiprocessing import Lock

class Show(Process):    #
    def run(self):
        with open(ticket) as f:
            dic = json.load(f)
            print("余票:{}".format(dic[ticket]))

class Buy_ticket(Process):  #
    def __init__(self,name,lock):   #接收锁对象
        super().__init__()
        self.name = name
        self.lock = lock
    def run(self):
        self.lock.acquire()     #拿钥匙进门
        with open(ticket) as f:
            dic = json.load(f)
            time.sleep(0.1) #模拟网络延迟
        if dic[ticket] > 0:
            dic[ticket] -=1
            print({}买到票了~~~.format(self.name))
            time.sleep(0.1) #模拟网络延迟
            with open(ticket,w) as f:
                json.dump(dic,f)
        else:
            print({}没买到票!!!.format(self.name))
        self.lock.release()     #还钥匙
if __name__ == __main__:
    for i in range(10):
        q1 = Show()
        q1.start()
    lock = Lock()   #定义一个锁对象
    for i in range(10):
        i = str(i)
        q2 = Buy_ticket(i,lock) #将锁对象传入子进程
        q2.start()

json文件:技术图片结果:技术图片就只有三个人买到了~~

python_并发编程——锁

标签:span   网络   start   elf   init   class   sleep   color   RoCE   

原文地址:https://www.cnblogs.com/wangdianchao/p/12044316.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!