作为标题提到
示例代码:
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()
我想让工人处理两件事:
但这两个都是块调用
我该怎么办,让工人同时从袜子里排队?
答案 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()