# 第 21 章 协程原理

> 学完这章，你能用 `create/resume/yield` 写生产者-消费者与生成器，并说清协程为什么不是线程。

## 本章目标

- [ ] 能说明协程是独立栈的 `thread`，非抢占、不并行
- [ ] 能使用 `create/resume/yield/status/wrap/close`
- [ ] 能写生产者-消费者、生成器、双向 resume
- [ ] 能解释 `resume` 返回 `(true, ...)` 与 `wrap` 的差异
- [ ] 能说明 `yield` 的跨 C 边界限制
- [ ] 能识别协程的常见误用

## 前置知识

- 第 07 章（函数/多重返回）、第 12 章（迭代器）、第 20 章（错误处理）。

## 从你熟悉的语言出发

| 概念 | Go | Java | JS | Lua 的差异 |
| --- | --- | --- | --- | --- |
| 并发单元 | goroutine | 线程/虚拟线程 | Promise/事件循环 | 协程（thread） |
| 调度 | 抢占式 | 抢占式 | 事件循环 | **协作式**，手动 resume |
| 让出 | 自动 | 自动 | `await` | `yield` |
| 传值 | channel | 队列 | Promise | resume/yield 双向传值 |
| 并行 | 多核 | 多核 | 单线程 | 单线程（宿主可多线程） |

Lua 协程是「可以暂停/恢复的函数」，只有被调用者能让出，调度权在调用方。Go 的 goroutine 由运行时抢占调度，能并行；Lua 协程不并行，长计算会阻塞同进程所有协程。

## 正文

### 21.1 创建、恢复、让出

```lua
local co = coroutine.create(function(a)
	local b = coroutine.yield(a + 1)
	return b * 2
end)
print(coroutine.resume(co, 10))   --> true	11
print(coroutine.resume(co, 5))    --> true	10
print(coroutine.status(co))       --> dead
```

```text
true	11
true	10
dead
```

第一次 `resume(co, 10)` 启动函数，参数 `a=10`；`yield(a+1)` 让出 11。第二次 `resume(co, 5)` 把 5 作为 `yield` 的返回值赋给 `b`，函数继续到 `return 10`。`resume` 总是返回 `true/false` 加后续值，错误不会直接抛给调用方。

### 21.2 状态与生命周期

`coroutine.status(co)` 返回：

- `suspended`：未启动或已让出，可 resume。
- `running`：正在执行（协程内部看自己）。
- `normal`：resume 了另一个协程（当前协程被挂起）。
- `dead`：结束或出错，不能再 resume。

`coroutine.close(co)`（5.4）关闭 suspended 协程，触发其 `<close>` 清理；对 dead 协程也可调用。关闭后不能 resume。

### 21.3 `wrap` 与生成器

`coroutine.wrap(f)` 返回一个函数，调用它等于 `resume`，但**错误会直接抛出**而不是返回 `false`：

```lua
local gen = coroutine.wrap(function()
	for i = 1, 3 do
		coroutine.yield(i)
	end
end)
for value in gen do
	print(value)
end
```

```text
1
2
3
```

`wrap` 适合生成器/迭代器；`create` 适合需要检查错误、控制状态的场景。`for` 循环提前 `break` 不会关闭协程，资源清理要显式 `close` 或让协程自然结束。

### 21.4 生产者-消费者与管道

```lua
local function producer()
	for i = 1, 3 do
		coroutine.yield(i)
	end
	return "done"
end
local co = coroutine.create(producer)
while true do
	local ok, value = coroutine.resume(co)
	assert(ok, value)
	if coroutine.status(co) == "dead" then
		break
	end
	print(value)
end
```

```text
1
2
3
```

消费者驱动生产者，每次 `resume` 取一个值。可以把多个生成器串成管道（filter/map），但每层都是手动 resume；没有 `await` 语法。

### 21.5 双向通信

`resume` 的参数传给 `yield` 的返回值，`yield` 的参数传给 `resume` 的返回值。这让协程可以当状态机：

```lua
local co = coroutine.create(function()
	local command = coroutine.yield("ready")
	while command ~= "stop" do
		command = coroutine.yield("got " .. command)
	end
end)
print(coroutine.resume(co))              --> true	ready
print(coroutine.resume(co, "work"))      --> true	got work
```

### 21.6 限制与陷阱

- 协程不并行；CPU 密集任务要拆分/让出，否则阻塞。
- `yield` 不能跨 C 调用边界（除非 C 函数用 `lua_yieldk` + continuation）；`pcall`/元方法在 5.4 允许 yield，但 C 扩展要小心。
- 协程出错后状态为 dead，错误通过 `resume` 返回；`wrap` 则抛出。
- 协程栈独立，但共享全局/upvalue；数据竞争在宿主多线程时才出现。
- 不要用协程实现「线程池」；它是控制流工具，不是并行原语。

### 21.7 调度与宿主

Lua 核心没有调度器；需要自己写 round-robin（第 22 章），或由宿主事件循环驱动（OpenResty/Neovim）。协程只在 `yield` 点切换，长时间计算会饿死其它任务；把大任务切片是调用方的责任。

### 21.8 协程里的错误与清理

协程内 `error` 会让 `resume` 返回 `false, err`，协程进入 dead；`wrap` 则把错误抛给调用方。协程里的 `pcall` 可以捕获并继续，但 `yield` 跨 `pcall` 的行为在 5.4 才放宽，C 扩展需注意。

`suspended` 协程可能持有文件/锁；`coroutine.close`（5.4）会触发 to-be-closed 变量清理，并让协程变 dead。LuaJIT 没有 `close`，只能依赖 GC/显式协议；跨运行时库要把清理做成显式接口。

### 21.9 何时不该用协程

协程适合「有多个暂停点的线性流程」：解析器、生成器、状态机、异步 IO 的同步写法。不适合：纯计算并行（没有并行）、简单循环（增加复杂度）、需要抢占的任务（长计算会饿死别人）。如果一段代码只在末尾返回一次，用函数即可；协程的价值在「多次让出」。判断标准是「是否需要在中间保存执行位置」，而不是「是否想写得像 async」。把协程当控制流工具，代码的可读性与清理逻辑都更容易维护；反之，为了「异步风格」强行包协程，只会让栈与错误路径更难追踪，测试也不容易覆盖所有让出点，团队维护成本反而更高；先写普通函数，确有多暂停点再引入协程。这条原则能避免大部分「过度异步」的复杂度。把协程留给真正需要暂停/恢复的流程，普通逻辑保持函数式写法，代码更容易测试，确实非常优秀，很好。

## 报错现场

在协程外调用 `yield`：

```lua
coroutine.yield(1)
```

真实输出（Lua 5.4.9，macOS arm64）：

```text
lua: attempt to yield from outside a coroutine
stack traceback:
	[C]: in function 'coroutine.yield'
	yield.lua:1: in main chunk
	[C]: in ?
```

逐行读：

- `attempt to yield from outside a coroutine`：主 chunk 不是协程，不能 yield。
- `[C]: in function 'coroutine.yield'`：yield 是 C 函数。
- 修法：把代码放进 `coroutine.create(function() ... end)` 或 `wrap`。
- 同类：对 dead 协程 `resume` 返回 `false, "cannot resume dead coroutine"`，不会抛错。

## 反直觉差异：协程不是线程，`resume` 第一个返回值是布尔

**你的直觉**：协程像 goroutine，`resume` 应该直接返回协程的返回值；多个协程并行跑。

**实际行为**：

```lua
local co = coroutine.create(function() return 42 end)
print(coroutine.resume(co))   --> true	42
print(coroutine.resume(co))   --> false	cannot resume dead coroutine
```

```text
true	42
false	cannot resume dead coroutine
```

协程不并行，只在 resume 时执行；完成后 dead，不能复活。`resume` 用布尔区分「成功/失败」，后续才是值/错误。

**为什么这样设计**：协程是控制流原语，不是调度单元；布尔返回值让调用方统一处理错误，而 `wrap` 提供「像函数一样」的简化接口。

**正确写法**：用 `create` 时检查 `ok`；用 `wrap` 时用 `pcall` 包住；把协程当「可暂停函数」，不要当线程池。需要并行用宿主线程/多进程。

## 示例索引

| 目录 | 演示什么 | 预期看到 |
| --- | --- | --- |
| `examples/21-coroutines/01-producer-consumer/` | resume/yield | `final=done` |
| `examples/21-coroutines/02-generator/` | `wrap` 生成器 | `sum=10` |
| `examples/21-coroutines/03-coroutine-status/` | 状态与 dead | `dead_err=...` |

## 练习题

1. 用 `wrap` 生成 1..n。见 `exercises/21-coroutines/01-range-generator/`。
2. 收集协程 yield 的全部值。见 `exercises/21-coroutines/02-producer/`。

<details><summary>参考答案</summary>

```lua
-- 1
function M.solve(n)
	return coroutine.wrap(function()
		for i = 1, n do
			coroutine.yield(i)
		end
	end)
end

-- 2
function M.solve(co)
	local values = {}
	while true do
		local ok, value = coroutine.resume(co)
		assert(ok, value)
		if coroutine.status(co) == "dead" then
			return values
		end
		values[#values + 1] = value
	end
end
```

</details>

## 章末自检

1. 协程与线程的区别？
2. `resume`/`yield` 如何双向传值？
3. `create` 与 `wrap` 的错误处理差异？
4. 四种状态分别何时出现？
5. 为什么 `yield` 不能随便跨 C 边界？
6. 协程结束后还能 resume 吗？
7. 提前 break 会关闭生成器吗？
8. 长计算对协程调度有什么影响？

<details><summary>答案要点</summary>

1. 协作式/非并行 vs 抢占式/并行。
2. resume 参数给 yield 返回值，yield 参数给 resume 返回值。
3. resume 返回 false,err；wrap 抛错。
4. suspended/running/normal/dead。
5. C 栈/continuation 限制。
6. 不能，dead。
7. 不会，需 close/自然结束。
8. 阻塞同进程其它协程。

</details>

## 延伸阅读

- Lua 5.4 Reference Manual §2.6 Coroutines
- Lua 5.4 Reference Manual §6.2 Coroutine Manipulation
- 第 12 章（迭代器）、第 22 章（调度）、第 32 章（宿主事件循环）
