一个线程写入队列,一个线程读取

时间:2015-08-10 22:21:05

标签: python windows queue multiprocessing python-multiprocessing

我试图让一个线程将项添加到队列中,而主线程将它们拉出来。在阅读多处理文档后,我尝试的方法并不起作用。我究竟做错了什么?谢谢。

import time
from multiprocessing import Process, Queue

def append_to_queue(q, t=1):
    n = 0
    while True:
        q.put(n)
        n += 1
        time.sleep(t)

def print_queue(q, t=0.5):
    while True:
        print q.get()
        time.sleep(t)

def main(t1, t2, delay=1):
    q = Queue()
    p = Process(target=append_to_queue, args=(q, t1,))
    p.start()
    time.sleep(delay)
    print_queue(q, t2)
    p.join()

main(1, 0.5, delay=1)

1 个答案:

答案 0 :(得分:1)

  1. 您正在使用流程而不是线程
  2. 您实际上是使用单个流程进行生产,但在主流程中只消耗一次。我想你想要一个消费过程。
  3. 这是一个演示:

    import time
    from multiprocessing import Process, Queue, Event
    
    def append_to_queue(t, q, stopnow):
        n = 0
        while not stopnow.is_set():
            q.put(n)
            n += 1
            time.sleep(t)
        q.put("producer done") # consumer will print this
    
    def print_from_queue(t, q, stopnow):
        while not stopnow.is_set():
            print q.get()
            time.sleep(t)
        # drain queue
        for msg in xrange(q.qsize()):
            print msg
        print "consumer done"
    
    def main(t1, t2):
        # @eryksun:
        # Because windows doesn't fork - the Queue
        # and Event can't be inherited from the main process.
        # Create them in main and pass them in the args tuple.
        q = Queue()
        stopnow = Event()
        producer = Process(target=append_to_queue, args=(t1, q, stopnow))
        producer.start()
        consumer = Process(target=print_from_queue, args=(t2, q, stopnow,))
        consumer.start()
        time.sleep(5)
        stopnow.set()
        producer.join()
        consumer.join()
    
    # @eryksun:
    # Windows doesn't fork, so you need to use if __name__ == '__main__'
    # to guard calling main
    if "__main__" == __name__:
        main(1, 0.5)