python中多程式消費者生產者問題

One of them發表於2018-08-23

multiprocessing消費,生產實現

"""
多程式.
Manager.Queue() 建立對列物件.
"""
from multiprocessing import Process
from multiprocessing import Manager
import random
import time


class Producer(Process):

    def __init__(self, queue):  # 重寫.
        super().__init__()  # 加入父類init.
        self.queue = queue

    def run(self):  # call start()時 就會呼叫run(run為單程式).
        while True:
            # print('1')
            item = random.randint(0, 99)  # left is closed and right is closed.
            self.queue.put(item)
            print("Producer-->%s" % item)
            time.sleep(1)


class Consumer(Process):
    def __init__(self, queue):  # 重寫.
        super().__init__()  # 加入父類init.
        self.queue = queue

    def run(self):  # call start()時 就會呼叫run(run為單程式).
        while True:
            # print("2")
            item = self.queue.get()
            print("Consumer-->%s" % item)
            self.queue.task_done()


if __name__ == '__main__':
    qMar = Manager()
    q1 = qMar.Queue()
    p = Producer(q1)
    c = Consumer(q1)
    p.start()
    c.start()
    p.join()
    c.join()

相關文章