Urgent.News

What's breaking now, across thousands of outlets.

Tech

协程到底是什么?用"一个人守三口锅"讲明白,别再和线程混为一谈

面试里被问"协程是什么",很多人的答案是一句背来的话:"协程是用户态的轻量级线程。" 这句话不算错,但它几乎解释不了任何事。听完之后你还是不知道该在什么时候用它、为什么它会被一个 time.sleep() 卡死、为什么它不需要锁。 这篇不讲定义,只讲三件事: 协程在切什么、调度权在谁手里、什么时候不该用。 一、先把三个词排成一队:进程、线程、协程 这三个东西经常被并列着讲,但它们回答的其实是同一个问题: "谁来决定现在跑哪段代码?" 进程 :操作系统给一个程序划的地盘,有自己独立的内存空间。切进程最贵,因为要换页表、换地址空间。 线程 :进程内部的执行流,共享同一片内存,但各自有独立的栈。切换要走操作系统(内核态),几十到几百纳秒起步,而且共享内存意味着你需要锁。 协程 :跑在 某一个线程内部…

What exactly is a coroutine and how does it differ from a thread? Many people mistakenly describe a coroutine as a lightweight user-level thread. However, this oversimplifies the concept. Unlike threads, which compete for CPU time and require careful handling of shared resources through locks, coroutines are designed for cooperative multitasking within a single thread.

They can be paused and resumed without relying on the operating system or needing locks, making them efficient for I/O-bound tasks. The key differences lie in how they are scheduled and the trade-offs they entail. Coroutines give up control explicitly, allowing the runtime to manage their execution flow, while threads are preemptively scheduled by the OS.

Understanding when to use coroutines versus threads depends on the nature of the workload—whether it's CPU-intensive or I/O-bound.

Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at dev.to →

More in Tech

An alternate-key lookup still needs object authorization

Most BOLA writeups show GET /orders/{id} with a guessed UUID. The same bug often hides behind a “friendlier” lookup: GET /orders?email= , findByExternalId , or where slug = ? .

  • Alternate-key lookups can expose object authorization flaws.
  • System should authorize loaded resource for specific subject.
  • Same denial shape as id-based routes prevents accidental oracles.

协程到底是什么?把它当成“一个能中途暂停的函数”,一切就通了

TL;DR:协程不是“更快的线程”,它是一个可以在中途停下来、把线程让给别人、之后还能从停下的那一行接着跑的函数。它省掉的不是计算时间,而是等 IO 时的空转。 面试被问“协程是什么”,大多数人的答案是背来的一句:“协程是用户态的轻量级线程。” 这句话不算错,但它几乎解释不了任何事。听完你还是不知道该在什么时候用它、为什么它会被一个 time.sleep() 卡死、为什么它不需要锁。…

More from Friday 2 October →