代码之家  ›  专栏  ›  技术社区  ›  Srini

树中生产者和消费者的队列

  •  1
  • Srini  · 技术社区  · 15 年前

    它的 父母…等等。

    我已经在这里和其他地方搜索和阅读了许多帖子…我了解所有的队列方法。我仍然不明白的是如何将队列关联或绑定到2个给定的节点。

    我希望节点1和节点2向节点3发送消息。对于这个基本场景,我必须以某种方式创建一个(或2个)队列,并将其与node-1和node-2“关联”,node-1和node-2使用它将消息放入node-3和node-3。而且,节点3还必须与该队列“侦听”/“关联”,才能“获取”或出列任务。

    如果node-1和node-2是“producer”,我应该将它们作为两个独立的线程,node-3是第三个线程。然后,我必须创建一个队列Q。然后,我应该让node-1和node-2创建消息,将它们“放入”队列。Node-3必须以某种方式被通知/唤醒,以便从Q“获取”这些消息并对其进行处理。

    我见过

    http://docs.python.org/library/queue.html#module-Queue

    =================================================================

    import threading
    import queue
    
    q = Queue.Queue(2)   # create a queue of size 2.
    
    # worker is node-3 which received msgs from 1 and 2 and fuses them.
    def worker():
        while True:
            msg = q.get()
            fuse_msgs(msg)
            q.task_done()
    
    # generate 3 worker threads. Node-3 could be both a producer and consumer. Each
    # thread represents each node that will be a potential producer/consumer or both.
    # need something like t1 - thread-1 for node-1 ...
    
    for i in range(3):
         t = Thread(target=worker)
         t.setDaemon(True)
         t.start()
    
    # How can I make node-1 and node-2 to put items into a specified queue???
    
    
    
    for msg in source():
        q.put(item)
    
    q.join()  
    

    =========================================

    我走的方向对吗?请让我知道我错在哪里,我误解了什么。。。

    B.R.斯里尼。

    1 回复  |  直到 12 年前
        1
  •  1
  •   zigdon    15 年前

    我并没有特别评论python代码,但就您的队列设计而言,您似乎只需要在您描述的node1、2、3场景中使用一个队列。基本上,您有一个队列,节点1和节点2将消息放入队列,节点3从队列中读取消息。

    您应该能够告诉node-3对队列执行“阻塞”操作,这样它就可以等到看到消息后再进行处理,并让node-1和node-2尽快生成它们的输出。