gpt4 book ai didi

python - Waitress 如何处理并发任务?

转载 作者:行者123 更新时间:2023-12-04 11:18:50 30 4
gpt4 key购买 nike

我正在尝试使用 Django 和 Waitress 构建一个 python 网络服务器,但我想知道 Waitress 如何处理并发请求,以及何时可能发生阻塞。

Waitress documentation提到有多个工作线程可用,它没有提供很多关于它们是如何实现的以及 python GIL 如何影响它们的信息(强调我自己的):

When a channel determines the client has sent at least one full valid HTTP request, it schedules a "task" with a "thread dispatcher". The thread dispatcher maintains a fixed pool of worker threads available to do client work (by default, 4 threads). If a worker thread is available when a task is scheduled, the worker thread runs the task. The task has access to the channel, and can write back to the channel's output buffer. When all worker threads are in use, scheduled tasks will wait in a queue for a worker thread to become available.



Stackoverflow 上似乎也没有太多信息。来自问题 "Is Gunicorn's gthread async worker analogous to Waitress?" :

Waitress has a master async thread that buffers requests, and enqueues each request to one of its sync worker threads when the request I/O is finished.



这些陈述没有解决 GIL(至少从我的理解来看),如果有人能详细说明工作线程如何为 Waitress 工作,那就太好了。谢谢!

最佳答案

以下是事件驱动的异步服务器通常的工作方式:

  • 启动一个进程并监听传入的请求。利用操作系统的事件通知 API 可以很容易地从单个线程/进程为数千个客户端提供服务。
  • 由于只有一个进程管理所有连接,因此您不希望在此进程中执行任何缓慢(或阻塞)的任务。因为那样它会为每个客户端阻塞程序。
  • 为了执行阻塞任务,服务器将任务委托(delegate)给“ worker ”。 worker 可以是线程(在同一进程中运行)或单独的进程(或子进程)。现在主进程可以继续为客户端服务,而 worker 执行阻塞任务。


  • How does Waitress handle concurrent tasks?



    几乎与我上面描述的方式相同。对于 worker ,它创建线程,而不是进程。

    how the python GIL affects them



    女服务员为 worker 使用线程。所以,是的,它们受到 GIL 的影响,因为它们虽然看起来是并发的,但它们并不是真正并发的。 “异步”是正确的术语。

    Python 中的线程在单个进程内、单个 CPU 内核上运行,并且不并行运行。一个线程在很短的时间内获取 GIL 并执行其代码,然后另一个线程获取 GIL。

    但是由于 GIL 是在网络 I/O 上释放的,所以每当有网络事件(例如传入请求)时,父进程将始终获取 GIL,这样您就可以放心 GIL 不会影响网络绑定(bind)操作(如接收请求或发送响应)。

    另一方面,Python 进程实际上是并发的:它们可以在多个内核上并行运行。但是女服务员不使用流程。

    你应该担心吗?

    如果你只是做一些小的阻塞任务,比如数据库读/写,并且每秒只为几百个用户提供服务,那么使用线程并不是那么糟糕。

    为了服务大量用户或执行长时间运行的阻塞任务,您可以考虑使用外部任务队列,如 Celery .这比自己生成和管理流程要好得多。

    关于python - Waitress 如何处理并发任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59838433/

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