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

7.15python进程锁

时间:2018-07-15 19:46:25      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:import   start   open   rgs   target   lse   art   pytho   env   

#!/usr/bin/env python
#!--*--coding:utf-8 --*--
#!@Time    :2018/7/14 17:33
#!@Author   TrueNewBee
#

# 火车票
import json
import time
from multiprocessing import Process
from multiprocessing import Lock

def show(i):
    with open(ticket) as f:
        dic = json.load(f)
    print(余票: %s%dic[ticket])

def buy_ticket(i,lock):
    lock.acquire() #拿钥匙进门
    with open(ticket) as f:
        dic = json.load(f)
        time.sleep(0.1)
    if dic[ticket] > 0 :
        dic[ticket] -= 1
        print(\033[32m%s买到票了\033[0m%i)
    else:
        print(\033[31m%s没买到票\033[0m%i)
    time.sleep(0.1)
    with open(ticket,w) as f:
        json.dump(dic,f)
    lock.release()      # 还钥匙

if __name__ == __main__:
    for i in range(10):
        p = Process(target=show,args=(i,))
        p.start()
    lock = Lock()
    for i in range(10):
        p = Process(target=buy_ticket, args=(i,lock))
        p.start()

天真热,,天干物燥,!  要安安静静多看书!

7.15python进程锁

标签:import   start   open   rgs   target   lse   art   pytho   env   

原文地址:https://www.cnblogs.com/zhen1996/p/9314213.html

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