随着时间的推移,Stackless Python网络性能是否会下降?

8
我正在使用Stackless Python玩耍,编写一个非常简单的Web服务器来教自己使用微线程/任务。但我遇到了问题,当我运行类似于ab -n 100000 -c 50 http://192.168.0.192/(100,000个请求,50并发)时,在Apache bench中会得到大约6k req/s的结果,第二次运行时我得到5.5k,第三次5k,第四次4.5k等等,一直下降到大约100req/s。
然而,当我重新启动Python脚本时,这个问题就消失了。
现在我的问题是为什么?我是否忘记删除tasklets?我已经检查了stackless.getruncount()(出于某种原因,它似乎总是返回1),所以似乎没有任何死掉的tasklets悬挂?我尝试调用.done()函数来结束所有已完成的tasklets,但这并没有帮助。我只是无法解决这个问题。
import socket
import select
import stackless
import time

class socket_wrapper(object):
    def __init__(self, sock, sockets):
        super(socket_wrapper, self).__init__()
        self.sock = sock
        self.fileno = sock.fileno
        self.sockets_list = sockets
        self.channel = stackless.channel()
        self.writable = False
        self.error = False

    def remove(self):
        self.sock.close()
        self.sockets_list.remove(self)

    def send(self, data):
        self.sock.send(data)

    def push(self, bytes):
        self.channel.send(self.sock.recv(bytes))

def stackless_accept(accept, handler, recv_size=1024, timeout=0):
    sockets = [accept]

    while True:
        read, write, error = select.select(sockets, sockets, sockets, timeout)

        for sock in read:
            if sock is accept:
                # Accept socket and create wrapper
                sock = socket_wrapper(sock.accept()[0], sockets)

                # Create tasklett for this connection
                tasklet = stackless.tasklet(handler)
                tasklet.setup(sock)

                # Store socket
                sockets.append(sock)

            else:
                # Send data to handler
                sock.push(recv_size)

        # Tag all writable sockets
        for sock in write:
            if sock is not accept:
                sock.writable = True

        # Tag all faulty sockets
        for sock in error:
            if sock is not accept:
                sock.error = True
            else:
                pass # should do something here if the main socket is faulty

        timeout = 0 if socket else 1
        stackless.schedule() 

def simple_handler(tsock):
    data = ""

    while data[-4:] != "\r\n\r\n":
        data += tsock.channel.receive()

    while not tsock.writable and not tsock.error:
        stackless.schedule()

    if not tsock.error:
        tsock.send("HTTP/1.1 200 OK\r\nContent-length: 8\r\n\r\nHi there")
        tsock.remove()

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(("192.168.0.192", 8000))
sock.listen(5)

stackless.tasklet(stackless_accept)(sock, simple_handler)
stackless.run()
1个回答

14

两件事情。

首先,请让类名以大写字母开头。这样更传统且更易于阅读。

更重要的是,在stackless_accept函数中,您正在累积一个名为socketsSock对象列表。该列表似乎会无限增长。是的,您有一个remove,但它并不总是被调用。如果套接字出现错误,则似乎将永远留在集合中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接