关于单线程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


实验说明一切。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值