Files
eino-test/data/go-concurrency.md
T

47 lines
1.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
tags: [go, concurrency, goroutine]
---
## Go 并发模式概述
Go 语言的并发模型基于 CSP(Communicating Sequential Processes)理论,核心思想是"通过通信共享内存,而不是通过共享内存通信"。
## Goroutine 基础
Goroutine 是 Go 运行时管理的轻量级线程。创建一个 goroutine 只需要在函数调用前加上 `go` 关键字:
```go
go func() {
fmt.Println("Hello from goroutine")
}()
```
Goroutine 的初始栈大小只有 2KB,远小于操作系统线程的 1-2MB,因此可以轻松创建数十万个 goroutine。
## Channel 通信
Channel 是 goroutine 之间通信的管道:
```go
ch := make(chan int, 10) // 带缓冲的 channel
ch <- 42 // 发送
value := <-ch // 接收
```
## 常见并发模式
### Fan-out/Fan-in
将任务分发给多个 goroutine 并行处理,然后汇总结果。
### Pipeline
将处理流程分成多个阶段,每个阶段是一个 goroutine,通过 channel 串联。
### Worker Pool
固定数量的 worker goroutine 从任务队列中取任务执行。
## 常见陷阱
1. **Goroutine 泄漏**:goroutine 阻塞在 channel 上无法退出
2. **Race Condition**:多个 goroutine 同时读写共享变量
3. **Deadlock**:所有 goroutine 都在等待对方