一、Queue是通过multiprocessing使用
from multiprocessing import Process,Queue
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))
def producer(q):
    for i in range(5):
        time.sleep(2)
        res='包子%s' %i
        q.put(res)
        print('\033[44m%s 制造了 %s\033[0m' %(os.getpid(),res))
    q.put(None)
if __name__ == '__main__':
    q=Queue()
    #生产者们:厨师们
    p1=Process(target=producer,args=(q,))

    #消费者们:吃货们
    p2=Process(target=consumer,args=(q,))

    p1.start()
    p2.start()
    p1.join()
    p2.join()
    print('')
生产者,消费者模型1
from multiprocessing import Process,Queue
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))
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))
def product_jiaozi(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))
def product_dabing(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))
if __name__ == '__main__':
    q=Queue()
    #生产者们:厨师们
    p1=Process(target=product_baozi,args=(q,))
    p2=Process(target=product_jiaozi,args=(q,))
    p3=Process(target=product_dabing,args=(q,))
    #消费者们:吃货们
    p4=Process(target=consumer,args=(q,))
    p5=Process(target=consumer,args=(q,))

    p_l=[p1,p2,p3,p4,p5]
    for p in p_l:
        p.start()
    # for p in p_l:
    #     p.join()
    # p1.start()
    # p2.start()
    # p3.start()
    # p4.start()
    # p5.start()
    p1.join()
    p2.join()
    p3.join()
    q.put(None)
    q.put(None)
    p4.join()
    p5.join()
    print('')
生产者,消费者模型2

相关文章:

  • 2022-01-16
  • 2022-12-23
  • 2021-11-27
  • 2021-11-24
  • 2021-12-28
  • 2021-12-13
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-06
  • 2021-05-22
相关资源
相似解决方案