gpt4 book ai didi

python - 为什么Django Channels Daphne不能使用多线程并发处理请求?

转载 作者:行者123 更新时间:2023-12-01 09:22:06 31 4
gpt4 key购买 nike

我知道 Python 的 GIL 并且 Python 中的线程并不像在 Go 中生成 go 例程那么容易。然而,在我看来,Ruby 能够与 Puma 和 Unicorn 一起实现多线程并发。我的问题实际上有两个方面。我的经验仅限于 Django Channel 的 Daphne。

  1. 除了Daphne之外,Rails中的puma和unicorn等多线程Web服务器还有哪些选择?

  2. 从 Daphne 的文档中,我了解到并行性是通过生成新进程(工作进程)来实现的

    Because the work of running consumers is decoupled from the work of talking to HTTP, WebSocket and other client connections, you need to run a cluster of “worker servers” to do all the processing. Each server is single-threaded, so it’s recommended you run around one or two per core on each machine; it’s safe to run as many concurrent workers on the same machine as you like, as they don’t open any ports (all they do is talk to the channel backend).

如上所述,每个工作线程都是单线程的。当涉及到I/O函数调用时,worker完全被阻塞。我的问题是,为什么 Daphne 不能为每个请求生成多个线程。当一个线程被 I/O 阻塞时,例如当数据库访问时,CPU会切换到执行另一个线程,直到前一个线程被解除阻塞。同样,Node.js 是单线程的,但它通过非阻塞 I/O 很好地实现了并发性。为什么很难实现同样的壮举。在Python中? (除了它缺乏良好的事件循环这一事实。)

最佳答案

现在,uvicorn是 daphne 的唯一替代方案,支持多重处理并可供生产使用。

$ pip install uvicorn

$ uvicorn avilpage.asgi --workers 4

这将启动具有 4 个工作线程的服务器。

由于 daphne/uvicorn 使用 asyncio 进行多任务处理,我猜多线程没有意义。

关于python - 为什么Django Channels Daphne不能使用多线程并发处理请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50734957/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com