进程互斥锁

互斥锁:解决的问题是,共享的资源就会有竞争,所以把加上锁,记得要解锁哦

关键字:

mutex = Lock()

mutex.acquire()

要加锁的程序

mutex.release()

几个互斥锁的应用!

互斥锁模拟上厕所

from multiprocessing import Process,Lock
import time
import os
import random

def func(l):
    l.acquire()
    print('%s 正在上厕所' % os.getpid())
    time.sleep(random.randint(1, 4))
    print('%s 上完厕所了' % os.getpid())
    l.release()

if __name__ == '__main__':
    l = Lock()
    p1 = Process(target=func, args=(l,))
    p2 = Process(target=func, args=(l,))
    p3 = Process(target=func, args=(l,))

    p1.start()
    p2.start()
    p3.start()

    print('')

模拟抢票

from multiprocessing import Process,Lock
import json
import time
import random
import os

#查票功能
def search():
    dic = json.load(open('db.txt',))
    print('剩余票数%s' % dic['count'])


#买票功能
def get_ticket():
    dic = json.load(open('db.txt'))
    if dic['count'] > 0:
        dic['count'] -= 1
        json.dump(dic, open('db.txt', 'w'))
        print('%s 购票成功' % os.getpid())


#模拟付款交钱所花的时间
def task(mutex):
    search()
    time.sleep(random.randint(1, 3)) #模拟购票一系列繁琐的过程所花费的时间

    mutex.acquire()
    get_ticket()
    mutex.release()

if __name__ == '__main__':
    mutex = Lock()
    for i in range(20):
        p = Process(target=task, args=(mutex,))
        p.start()

队列:关键字:模块Queue

队列:共享的,并且自带锁功能

队列的应用:生产者消费者模型

#生产者消费者模型2
from multiprocessing import Process,JoinableQueue
import time
import random
import os

#消费者
def consumer(q):
    while True:
        res = q.get()
        if res is None:break
        time.sleep(random.randint(1,3))
        print('\033[45m%s 吃了 %s\033[0m' % (os.getpid(), res))
        q.task_done()


#生产者
def product_baozi(q):
    for i in range(3):
        time.sleep(2)
        res = '包子%s' % i
        q.put(res)
        print('\033[44m%s 制造了 %s\033[0m' %(os.getpid(),res))
    q.join()


def product_gutou(q):
    for i in range(3):
        time.sleep(2)
        res = '骨头%s' % i
        q.put(res)
        print('\033[44m%s 制造了 %s\033[0m' % (os.getpid(), res))
    q.join()


def product_ganshui(q):
    for i in range(3):
        time.sleep(2)
        res = '泔水%s' %i
        q.put(res)
        print('\033[44m%s 制造了 %s\033[0m' % (os.getpid(), res))
    q.join()


if __name__ == '__main__':
    q = JoinableQueue()
    #生产者们:厨师们
    p1 = Process(target=product_baozi, args=(q,))
    p2 = Process(target=product_gutou, args=(q,))
    p3 = Process(target=product_ganshui, args=(q,))

    #消费者们:吃货们
    p4 = Process(target=consumer, args=(q,))
    p5 = Process(target=consumer, args=(q,))
    p1.start()
    p2.start()
    p3.start()

    p4.daemon = True
    p5.daemon = True
    p4.start()
    p5.start()

    p1.join()
    p2.join()
    p3.join()
    print('')

 

posted @ 2017-08-28 18:32  Python界-黄药师  阅读(185)  评论(0编辑  收藏  举报