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

Posted 侯昂-py7

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了生产者消费者模型----------基于多进程多线程单线程并发相关的知识,希望对你有一定的参考价值。

生产者消费者模型
技术分享
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())
单线程下实现并发

 

以上是关于生产者消费者模型----------基于多进程多线程单线程并发的主要内容,如果未能解决你的问题,请参考以下文章

多进程生产者消费者框架设计

多进程生产者消费者框架设计

多进程生产者消费者框架设计

多线程生产者消费者模型

Java总结——通过Callable接口实现多线程,生产者消费者问题,多线下载(复制)文件

python 复习—并发编程实战——多线程和多进程的生产者消费者模型线程进程再总结