python 线程或多处理是异步调用的核心吗?

Is python threading or multiprocessing at core of async calls?

我已经使用过 python 异步框架,例如 Twisted 和 Tornado。我还知道 python 已经通过 asyncio 模块实现了异步调用的本机实现。我认为(线程,多处理)和异步调用是不同的概念。但不久前我看了几个与线程和多处理相关的视频,似乎所有这些异步人员都建立在它们之上。是真的吗?

不,一般来说async就是single-threaded,要实现async绝对不需要使用进程的多线程(这就是async的意义所在)。但在某些用例中,人们可能出于任何原因希望将它们混合在一起。

In this model [the async model], the tasks are interleaved with one another, but in a single thread of control. This is simpler than the threaded case because the programmer always knows that when one task is executing, another task is not. Although in a single-processor system a threaded program will also execute in an interleaved pattern, a programmer using threads should still think in terms of Figure 2, not Figure 3, lest the program work incorrectly when moved to a multi-processor system. But a single-threaded asynchronous system will always execute with interleaving, even on a multi-processor system.

来源:http://krondo.com/?p=1209

不,异步调用是构建程序的方式。 threadingmultiprocessing 可用于 实现 其中一些调用(但它们在 Python 异步框架中既不必要也不常见)。

Concurrency is not parallelism:

In programming, concurrency is the composition of independently executing processes, while parallelism is the simultaneous execution of (possibly related) computations

不要混淆程序文本的组织方式和实现(或执行)方式。完全相同的异步代码可以在单个线程、多个线程、多个进程中执行。在使用 multiprocessing.Pool(进程)、multiprocessing.dummy.Pool(线程)或它们的 gevent 补丁版本(single-threaded)的简单 Pool 代码之间切换很容易).此外,如果只有一个 CPU,则进程不一定 并行 ,但 OS 可以使它们 运行 同时.

如果 async 是指 Python 中的 async 关键字,那么它表示生成器函数——只是创建可等待对象的方法之一。 asyncio 不是使用此类对象的唯一方法,例如 curio which uses async functions but the backend is independent from asyncio. Recommended video: Python Concurrency From the Ground Up: LIVE!.