简体   繁体   English

gevent队列因LoopExit失败

[英]gevent queue failed with LoopExit

I want to use python gevent library to implement one producer and multiple consumers server. 我想使用python gevent库来实现一个生产者和多个消费者服务器。 There is my attempt: 我有尝试:

class EmailValidationServer():
   def __init__(self):
      self.queue = Queue()
   def worker(self):
      while True:
          json = self.queue.get()
   def handler(self,socket,address):
      fileobj = socket.makefile()
      content = fileobj.read(max_read)
      contents = json.loads(content)
      for content in contents:
          self.queue.put(content)
   def daemon(self,addr='127.0.0.1',num_thread=5):
      pool = Pool(1000)
      server = StreamServer((addr, 6000),self.handler,spawn=pool) # run
      pool = ThreadPool(num_thread)
      for _ in range(num_thread):
          pool.spawn(self.worker)
      server.serve_forever()
if __name__ == "__main__":
    email_server = EmailValidationServer()
    email_server.daemon()

I used the queue from gevent.queue.Queue. 我使用了来自gevent.queue.Queue的队列。 It gives me the error information: 它给我错误信息:

LoopExit: This operation would block forever
(<ThreadPool at 0x7f08c80eef50 0/4/5>,
 <bound method EmailValidationServer.worker of <__main__.EmailValidationServer instance at 0x7f08c8dcd998>>) failed with LoopExit

Problem: But when I change the Queue from gevent's implementation to python build-in library, it works. 问题:但是,当我将队列从gevent的实现更改为python内置库时,它可以工作。 I do not know the reason, I guess it's supported to have difference between their implementation. 我不知道原因,我想支持在它们的实现之间有所区别。 I do not know the reason why gevent does not allow infinite wait. 我不知道gevent不允许无限等待的原因。 Is there anyone can give an explanation? 有没有人可以解释? Thanks advance 谢谢前进

I suggest that you could use the gevent.queue.JoinableQueue() instead of Python's built-in Queue() . 我建议您可以使用gevent.queue.JoinableQueue()代替Python的内置Queue() You can refer to the official queue guide for API Usages ( http://www.gevent.org/gevent.queue.html ) 您可以参考API使用的官方队列指南( http://www.gevent.org/gevent.queue.html

def worker():
    while True:
        item = q.get()
        try:
            do_work(item)
        finally:
            q.task_done()

q = JoinableQueue()
for i in range(num_worker_threads):
     gevent.spawn(worker)

for item in source():
    q.put(item)

q.join()  # block until all tasks are done

If you met the exceptions again, you'd better get fully understand the principle of Gevent corouinte control flow ...Once you get the point, that was not a big deal. 如果再次遇到异常,则最好完全理解Gevent例程控制流的原理。。。一旦掌握了要点,那就没什么大不了的了。 :) :)

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

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