Abh*_*k G 4 python multithreading python-3.x async-await python-asyncio
Im trying to get more familiar in the usage of asyncio in python3, but I dont see when i should use async/await or threading. Is there a difference or is one just easier to use than the other.
So for example between these two functions, is one better than the other?
Just generic code
def func1()
def func2()
threads = [threading.Thread(target=func1), threading.Thread(target=func2)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
Run Code Online (Sandbox Code Playgroud)
versus
async def func1()
async def func2()
await asyncio.gather(func1(), func2())
Run Code Online (Sandbox Code Playgroud)
我的建议是在所有情况下都使用线程,除非您正在编写高性能并发应用程序并且基准测试表明单独使用线程太慢。
原则上,协程有很多值得喜欢的地方。它们更容易推理,因为每个非阻塞操作序列都可以被视为原子操作(至少如果您不将它们与线程结合起来);而且因为它们很便宜,所以您可以随意地旋转它们以更好地分离关注点,而不必担心会影响您的性能。
然而,Python 中协程的实际实现却是一团糟。最大的问题是,每个可能阻塞的函数,或者可能调用任何可能阻塞的代码,或者可能调用任何可能调用任何可能阻塞的代码的代码,都必须使用 和 关键字async重写await。这意味着,如果您想使用一个会阻塞的库,或者回调到您的代码并且您想在回调中阻塞,那么您根本无法使用该库。由于这个原因,现在 CPython 发行版中有一堆库的重复副本,甚至内置语法(async for等)的重复副本,但你不能指望通过 pip 提供的大多数模块都在两个版本。
线程不存在这个问题。如果某个库未设计为线程安全的,您仍然可以在多线程程序中使用它,方法是将其使用限制在一个线程中,或者使用锁保护所有使用。
因此,尽管线程存在问题,但总的来说,在 Python 中使用线程要容易得多。
有一些第三方协程解决方案可以避免“异步感染”问题,例如greenlet,但您仍然无法将它们与内部阻塞的库一起使用,除非它们是专门设计用于与协程一起使用的。
| 归档时间: |
|
| 查看次数: |
1794 次 |
| 最近记录: |