为什么gevent spawn不能正常工作呢?

时间:2013-01-18 06:31:08

标签: python gevent

当我远程登录到服务器并键入内容时,我希望输出在“spawn”之后打印,然后在“睡眠后”打印,但它会反过来。为什么会那样?我该如何解决呢?

import sys, signal
from gevent.server import StreamServer
from gevent.pool import Pool
from gevent import monkey
import gevent

def signal_handler(signal, frame): sys.exit(0)

class SocketPool(object):

    def __init__(self): self.pool = Pool(1000)

    def listen(self, socket):
        while True:
            line = socket.recv(1024)
            if not line:
                socket.close()
                break
            gevent.spawn(self.wait).join()
            print 'after spawn'

    def add_handler(self, socket, address):
        if self.pool.full(): raise Exception("At maximum pool size")
        else: self.pool.spawn(self.listen, socket)

    def wait(self):
        gevent.sleep(7)
        print 'after sleep'

    def shutdown(self): self.pool.kill()

signal.signal(signal.SIGINT, signal_handler)
monkey.patch_all()
sockPool = SocketPool()
server = StreamServer(('127.0.0.1', 5000), sockPool.add_handler)
server.serve_forever()

1 个答案:

答案 0 :(得分:3)

在生成greenlet后删除join调用。使用join,您将等待此greenlet完成。