1. 程式人生 > >關於單執行緒epoll模型伺服器的一點說明

關於單執行緒epoll模型伺服器的一點說明

現在的不少高效能伺服器都是用epoll模型單執行緒的模式

它的優點在於:

1. 單執行緒避免了多執行緒切換帶來的上下文切換開銷

2. epoll 模型優於select是因為無需阻塞在等待io等待上,而是去處理前一個已經就緒的事件(前一個請求的資料已經到達了或者說是就緒的)

它只是無阻塞的網路模型,對於回撥函式,它依然是可以阻塞的。

因此如果回撥函式中有阻塞事件,多執行緒的執行效率可能優於單執行緒

測試方法:

使用ab壓測

ab -c 5 -n 10000 http://localhost:8080/

實驗1: 回撥函式中無阻塞

1) 單執行緒

from twisted.internet import epollreactor
epollreactor.install()

from twisted.internet import reactor
from twisted.web import server, resource
import time
class Simple(resource.Resource):
    isLeaf = True
    def render_GET(self, request):
        #time.sleep(0.5)
        return "<html>Hello, world!</html>"
import sys
print sys.modules['twisted.internet.reactor']
site = server.Site(Simple())
reactor.listenTCP(8080, site)
reactor.run()

2) 多執行緒

from twisted.internet import epollreactor
epollreactor.install()

from twisted.internet import reactor

from twisted.web import server
from twisted.web.wsgi import WSGIResource
from twisted.python.threadpool import ThreadPool
from twisted.application import service, strports
from twisted.web.server import Site
import time
# Create and start a thread pool,
wsgiThreadPool = ThreadPool()
wsgiThreadPool.start()

# ensuring that it will be stopped when the reactor shuts down
reactor.addSystemEventTrigger('after', 'shutdown', wsgiThreadPool.stop)
         
def application(environ, start_response):
    """A basic WSGI application"""
    #time.sleep(0.5)
    start_response('200 OK', [('Content-type','text/plain')])
    return ['hello world']

# Create the WSGI resource 
wsgiAppAsResource = WSGIResource(reactor, wsgiThreadPool, application)
    
    

reactor.listenTCP(8080, Site(wsgiAppAsResource))
reactor.run()

實驗結果:
型別 request/sec
單執行緒 1339.98
多執行緒 1047.78

實驗2: 回撥函式中有阻塞

只需加入sleep函式即可

time.sleep(0.5)

實驗結果:

型別 request/sec
單執行緒 1.99
多執行緒 9.90

實驗說明一切。