协程到底是什么?把它当成“一个能中途暂停的函数”,一切就通了
TL;DR:协程不是“更快的线程”,它是一个可以在中途停下来、把线程让给别人、之后还能从停下的那一行接着跑的函数。它省掉的不是计算时间,而是等 IO 时的空转。 面试被问“协程是什么”,大多数人的答案是背来的一句:“协程是用户态的轻量级线程。” 这句话不算错,但它几乎解释不了任何事。听完你还是不知道该在什么时候用它、为什么它会被一个 time.sleep() 卡死、为什么它不需要锁。 这篇不讲定义,只讲三件事: 协程在切什么、调度权在谁手里、什么时候不该用它。 一、先问一个更朴素的问题:谁在决定现在跑哪段代码? 进程、线程、协程经常被并列着讲,但它们回答的其实是同一个问题: “现在这一刻,CPU 该执行哪段代码,由谁说了算?” 谁在调度 切换成本 需要锁吗 能并行吗 进程 操作系统 最贵(换地址空间、页表) 需要(或靠 IPC) 能,真并行 线程 操作系统…
Coroutines are often misunderstood as "faster threads", but they are actually functions that can pause execution and release the thread to other tasks. Unlike threads, coroutines are not independent processes; they operate within a single thread. Their main benefit is in scenarios where a task is waiting for I/O, allowing other tasks to run during the wait. This is why many people mistakenly describe coroutines as "lightweight threads", which is true to some extent but doesn't fully explain their use cases or limitations.
Coroutines differ from threads in terms of context switching, locking, and parallel execution capabilities. Context switching in threads requires system-level intervention and locks to protect shared resources, while coroutines are managed within the same thread, avoiding heavy system overhead and the need for locks. However, this comes at the cost of requiring coroutines to manage their own scheduling points, as the operating system does not interrupt them unless explicitly programmed to do so.
The main advantages of using coroutines are in I/O-bound tasks, such as making multiple network requests or handling I/O-intensive operations within a web service. Coroutines shine in these scenarios because they can overlap the waiting periods of different tasks, making efficient use of threads. Conversely, they are not suitable for CPU-intensive tasks, which are better handled by traditional multi-processing techniques.
A common pitfall of coroutines is the risk of a blocking operation causing all coroutines in the same thread to halt. This can be mitigated by using non-blocking libraries, such as `asyncio.to_thread()`, which offload blocking tasks to a separate thread. It's crucial to identify whether a bottleneck is due to waiting for I/O or computation, and use coroutines accordingly. Properly leveraging coroutines can lead to significant performance gains in the right contexts, but they are not a panacea for all performance issues.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.