简体   繁体   English

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

[英]One thread writing to queue, one thread reading

I'm trying to get one thread to add items to a queue and the main thread to pull them off. 我正在尝试让一个线程将项目添加到队列,并通过主线程将其拉出。 The approach I'm trying, having read the multiprocessing docs isn't working. 我正在尝试的方法已经阅读了多处理文档,但没有用。 What am I doing wrong? 我究竟做错了什么? Thank you. 谢谢。

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. You're using processes not threads 您正在使用进程而不是线程
  2. You're actually using a single process for producing but you only consume once in your main process. 实际上,您使用的是单个流程进行生产,但在主要流程中仅消耗一次。 I think you want a consume process. 我认为您需要一个消费过程。

Here is a demo: 这是一个演示:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM