Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python “a”的数据类型;“可关闭”;为多个生产者和消费者处理项目流的队列_Python_Multithreading_Queue_Producer Consumer - Fatal编程技术网

Python “a”的数据类型;“可关闭”;为多个生产者和消费者处理项目流的队列

Python “a”的数据类型;“可关闭”;为多个生产者和消费者处理项目流的队列,python,multithreading,queue,producer-consumer,Python,Multithreading,Queue,Producer Consumer,是否有一种特定类型的队列是“可关闭的”,并且适用于有多个生产者、消费者,并且数据来自一个流(因此不知道何时结束) 我一直找不到实现这种行为的队列,也找不到它的名称,但它似乎是生产者-消费者类型问题的一个整体类型 例如,理想情况下,我可以编写这样的代码:(1)每个生产者会告诉队列何时完成,(2)消费者会盲目地调用阻塞get(),以及(3)当所有消费者都完成且队列为空时,所有生产者都会取消阻塞并收到“完成”通知: 作为代码,它看起来像这样: def produce(): for x in ran

是否有一种特定类型的队列是“可关闭的”,并且适用于有多个生产者、消费者,并且数据来自一个流(因此不知道何时结束)

我一直找不到实现这种行为的队列,也找不到它的名称,但它似乎是生产者-消费者类型问题的一个整体类型

例如,理想情况下,我可以编写这样的代码:(1)每个生产者会告诉队列何时完成,(2)消费者会盲目地调用阻塞get(),以及(3)当所有消费者都完成且队列为空时,所有生产者都会取消阻塞并收到“完成”通知:

作为代码,它看起来像这样:

def produce():
  for x in range(randint()):
    queue.put(x)
    sleep(randint())
  queue.close()  # called once for every producer

def consume():
  while True:
    try:
      print queue.get()
    except ClosedQueue:
      print 'done!'
      break

num_producers = randint()
queue = QueueTypeThatICantFigureOutANameFor(num_producers)
[Thread(target=produce).start() for _ in range(num_producers)]
[Thread(target=consume).start() for _ in range(random())

另外,我不是在寻找“毒丸”解决方案,即为每个消费者在队列中添加“完成”值——我不喜欢生产者需要知道有多少消费者的不雅观。

我称之为自锁队列

对于您的主要需求,请将队列与条件变量检查结合起来,以便在所有生产商都已腾空时正常锁定(关闭)队列:

class SelfLatchingQueue(LatchingQueue):
  ...
  def __init__(self, num_producers):
    ...

  def close(self):
    '''Called by a producer to indicate that it is done producing'''

    ... perhaps check that current thread is a known producer? ...

    with self.a_mutex:
      self._num_active_producers -= 1
      if self._num_active_producers <= 0:
        # Future put()s throw QueueLatched. get()s will empty the queue
        # and then throw QueueEmpty thereafter
        self.latch() # Guess what superclass implements this?
类自闭锁队列(闭锁队列):
...
定义初始化(自我、数字生产者):
...
def关闭(自我):
“由制作人调用,表示已完成制作”
... 也许可以检查当前线程是否是已知的生产者。。。
使用self.a_互斥体:
self.\u num\u active\u producer-=1

如果是self._num_active_producer是的,我最终选择了这条路线。最后,我对Queue.Queue进行了子类化,不得不从Python 2.7的Queue.Queue中复制并微妙地修改
get()
put()
。我认为Python3.x的队列应该更容易接受,但我目前仍停留在2.7上