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

生产者消费者模型----------基于多进程、多线程、单线程并发

时间:2017-10-20 21:40:22      阅读:334      评论:0      收藏:0      [点我收藏+]

标签:技术分享   process   alt   bbb   logs   rgs   log   --   gevent   

生产者消费者模型
技术分享
from multiprocessing import Process,Queue
import time,random
def producer(name,q):
    for i in range(1,11):
        ret = "泔水%s"%i
        q.put(ret)
        print("厨师%s生产了%s" % (name, ret))
        time.sleep(random.randint(0,2))
def customer(name,q):
    while True:
        ret = q.get()
        if ret ==None:break
        time.sleep(random.randint(1,2))
        print("顾客%s吃了%s"%(name,ret))
if __name__ == __main__:
    q =Queue()
    p = Process(target=producer,args=("egon",q))
    c = Process(target=customer,args=("alex",q))
    p.start()
    c.start()
    p.join()
    q.put(None)
    c.join()
    print("主进程")
基于进程
技术分享
from threading import Thread,current_thread
import queue
import time,random
def producer(name,q):
    for i in range(1,11):
        ret = "泔水%s"%i
        q.put(ret)
        print("厨师%s生产了%s" % (name, ret),current_thread().getName())
        time.sleep(random.randint(0,2))
def customer(name,q):
    while True:
        ret = q.get()
        if ret ==None:break
        time.sleep(random.randint(1,2))
        print("顾客%s吃了%s"%(name,ret),current_thread().getName())
if __name__ == __main__:
    q =queue.Queue()
    p = Thread(target=producer,args=("egon",q))
    c = Thread(target=customer,args=("alex",q))
    p.start()
    c.start()
    p.join()
    q.put(None)
    c.join()
    print("主线程")
基于线程
技术分享
from gevent import monkey;monkey.patch_all()
import gevent
import queue
import threading
import time,random
def producer(name,q):
    for i in range(1,11):
        ret = "泔水%s"%i
        q.put(ret)
        print("厨师%s生产了%s" % (name, ret),threading.current_thread().getName())
        time.sleep(random.randint(0,2))
def customer(name,q):
    while True:
        ret = q.get()
        if ret ==None:break
        time.sleep(random.randint(1,2))
        print("顾客%s吃了%s"%(name,ret),threading.current_thread().getName())
if __name__ == __main__:
    q =queue.Queue()
    g1 = gevent.spawn(producer,"egon",q)
    g2 = gevent.spawn(customer,"alex",q)

    g1.join()
    q.put(None)
    g2.join()
    print("主线程",threading.current_thread().getName())
单线程下实现并发

 

生产者消费者模型----------基于多进程、多线程、单线程并发

标签:技术分享   process   alt   bbb   logs   rgs   log   --   gevent   

原文地址:http://www.cnblogs.com/houangpy-7/p/7701202.html

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