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
原文地址:https://www.cnblogs.com/mzfly/p/13090473.html