zoukankan      html  css  js  c++  java
  • Queue 实现了多生产者、多消费者队列

    """
    Queue 实现了多生产者、多消费者队列
    """
    from multiprocessing import Process, Queue
    import os, time, random
    from threading import Thread
    
    q = Queue(30)
    
    
    # 写数据进程执行的代码:
    def write(w):
        f = []
        for i in range(1,11):
            f.append(Obj(w,i))
    
        while True:
            if not q.full():
                q.put(f.pop())
                if len(f) == 0:
                    break
    
    
    # 读数据进程执行的代码:
    def read(q):
        i = 1
        while True:
            if not q.empty():
                ps = q.get()
                if ps:
                    ps.run(i)
                if ps.i == 1:
                    break
                time.sleep(0.1)
                i += 1
            else:
                pass
    
    
    class Obj(object):
        def __init__(self,w, i):
            self.w = w
            self.i = i
    
        def run(self, j):
            # print(self.w, self.i, j,end='
    ')
            print(self.i)
            pass
    
    
    if __name__ == '__main__':
        tb = []
        for i in range(6):
            tb.append(Thread(target=read, daemon=True,args=(q,)))
    
        for t in tb:
            t.start()
    
        write('w1')
        write('w2')
        write('w3')
        print('put结束')
    
        while True:
            if q.empty():
                break
  • 相关阅读:
    js数组
    关于编程,程序员的一些语录
    css心得
    js函数
    一些电脑基础知识
    gnome3安装
    C学习小记
    ubuntu重装系统后
    elinks文字浏览器
    快捷方式
  • 原文地址:https://www.cnblogs.com/mzfly/p/13090473.html
Copyright © 2011-2022 走看看