【问题标题】:Cherrypy multithreading exampleCherrypy 多线程示例
【发布时间】:2011-03-11 00:34:24
【问题描述】:

我确实知道cherrypy 是一个多线程的并且也有一个线程池实现。
所以我想尝试一个显示多线程行为的示例。
现在假设我在根类中有一些函数,其余所有东西都已配置

def testPage(self, *args, **kwargs):
    current = threading.currentThread()
    print 'Starting ' , current
    time.sleep(5)
    print 'Ending ' ,current
    return '<html>Hello World</html>'

现在假设我在浏览器的 3-4 个标签中以 http://localhost:6060/root/testPage 的身份运行我的页面。
我得到的结果是

Starting <WorkerThread(CP WSGIServer Thread-10, started 4844)>
Ending <WorkerThread(CP WSGIServer Thread-10, started 4844)>
Starting <WorkerThread(CP WSGIServer Thread-7, started 4841)>
Ending <WorkerThread(CP WSGIServer Thread-7, started 4841)>
Starting <WorkerThread(CP WSGIServer Thread-10, started 4844)>
Ending <WorkerThread(CP WSGIServer Thread-10, started 4844)>

我可以清楚地理解它正在创建新线程来处理每个新请求,但我无法弄清楚为什么每次我得到
starting...ending..starting..ending
为什么不开始……开始……结束……有时结束
因为我的假设是 time.sleep 会使某个线程暂停,而另一个线程可以在那个时候执行。

【问题讨论】:

  • 您应该尝试使用特定的软件,例如httperf: httperf --server=127.0.0.1 --port=6060 --num-conn=50 --rate=10

标签: python multithreading cherrypy


【解决方案1】:

这几乎可以肯定是您的浏览器而不是 CherryPy 的限制。例如,Firefox 2 将向同一个域发出不超过 2 个并发请求,即使有多个选项卡也是如此。如果每个选项卡也都在获取一个网站图标...这会在您的处理程序上一次点击一次。

请参阅http://www.cherrypy.org/ticket/550 以获取具有类似源代码和更长证明的票证。

【讨论】: