gevent同时使用Queue get和socket recv

时间:2013-06-17 04:17:03

标签: python gevent

作为标题提到

示例代码:

import gevent
from gevent.queue import Queue

class Worker(gevent.Greenlet):
    def __init__(self, sock):
        self.queue = Queue()
        self.sock = sock
        super(Worker, self).__init__()

    def _run(self):
        self.running = True
        while self.running:
            msg_from_queue = self.queue.get()    # block call
            msg_from_sock = self.sock.recv(128)  # block call

worker = Worker(sock)
worker.start()

我想让工人处理两件事:

  1. 来自sock的消息recv
  2. 消息从队列中获取
  3. 但这两个都是块调用

    我该怎么办,让工人同时从袜子里排队?

2 个答案:

答案 0 :(得分:1)

我找到了一种方法:

class Worker(gevent.Greenlet):
    def _sock_recv(self):
        # ...
    def _queue_get(self):
        # ...
    def _run(self):
        recv = gevent.spawn(self._sock_recv)
        get = gevent.spawn(self._queue_get)
        gevent.joinall([recv, get])

答案 1 :(得分:0)

如何将Worker分成两个工人?

class QueueWorker(gevent.Greenlet):
    def __init__(self, queue):
        self.queue = queue
        super(QueueWorker, self).__init__()

    def _run(self):
        self.running = True
        while self.running:
            msg = self.queue.get()    # block call
            print 'queue:', msg


class SocketWorker(gevent.Greenlet):
    def __init__(self, sock):
        self.sock = sock
        super(SocketWorker, self).__init__()

    def _run(self):
        self.running = True
        while self.running:
            msg = self.sock.recv(128)  # block call
            print 'socket:', msg

worker1 = QueueWorker(queue)
worker1.start()
worker2 = SocketWorker(sock)
worker2.start()