1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
|
package main
import (
"context"
"fmt"
"runtime"
"sync"
"sync/atomic"
"time"
)
// 1. 长时间运行的goroutine
func longRunningTask(ctx context.Context, id int) {
fmt.Printf("任务 %d 开始\n", id)
for {
select {
case <-ctx.Done():
fmt.Printf("任务 %d 收到取消信号,正在清理...\n", id)
// 执行清理工作
time.Sleep(100 * time.Millisecond)
fmt.Printf("任务 %d 已停止\n", id)
return
default:
// 执行实际工作
fmt.Printf("任务 %d 正在工作...\n", id)
time.Sleep(500 * time.Millisecond)
}
}
}
// 2. 带超时的goroutine
func taskWithTimeout(id int, duration time.Duration) {
fmt.Printf("超时任务 %d 开始,超时时间: %v\n", id, duration)
ctx, cancel := context.WithTimeout(context.Background(), duration)
defer cancel()
done := make(chan bool)
go func() {
// 模拟工作
time.Sleep(2 * time.Second)
done <- true
}()
select {
case <-done:
fmt.Printf("超时任务 %d 正常完成\n", id)
case <-ctx.Done():
fmt.Printf("超时任务 %d 超时\n", id)
}
}
// 3. 工作池模式
type Job struct {
ID int
Data string
}
type Result struct {
Job Job
Output string
Error error
}
func worker2(id int, jobs <-chan Job, results chan<- Result, wg *sync.WaitGroup) {
defer wg.Done()
for job := range jobs {
fmt.Printf("Worker %d 处理任务 %d\n", id, job.ID)
// 模拟处理时间
time.Sleep(time.Duration(job.ID*100) * time.Millisecond)
result := Result{
Job: job,
Output: fmt.Sprintf("处理结果: %s", job.Data),
Error: nil,
}
results <- result
}
fmt.Printf("Worker %d 退出\n", id)
}
// 4. 生产者-消费者模式
func producer(data chan<- int, count int) {
defer close(data)
for i := 1; i <= count; i++ {
fmt.Printf("生产: %d\n", i)
data <- i
time.Sleep(100 * time.Millisecond)
}
fmt.Println("生产者完成")
}
func consumer(id int, data <-chan int, wg *sync.WaitGroup) {
defer wg.Done()
for value := range data {
fmt.Printf("消费者 %d 消费: %d\n", id, value)
time.Sleep(200 * time.Millisecond)
}
fmt.Printf("消费者 %d 退出\n", id)
}
// 5. 错误处理和恢复
func riskyTask(id int, wg *sync.WaitGroup, errors chan<- error) {
defer wg.Done()
defer func() {
if r := recover(); r != nil {
errors <- fmt.Errorf("任务 %d panic: %v", id, r)
}
}()
fmt.Printf("风险任务 %d 开始\n", id)
// 模拟可能panic的操作
if id == 3 {
panic("模拟panic")
}
// 模拟可能出错的操作
if id == 2 {
errors <- fmt.Errorf("任务 %d 执行失败", id)
return
}
time.Sleep(500 * time.Millisecond)
fmt.Printf("风险任务 %d 成功完成\n", id)
}
func main() {
// 1. 可取消的长时间运行任务
fmt.Println("=== 可取消的长时间任务 ===")
ctx, cancel := context.WithCancel(context.Background())
// 启动多个长时间运行的任务
for i := 1; i <= 3; i++ {
go longRunningTask(ctx, i)
}
// 让任务运行一段时间
time.Sleep(2 * time.Second)
// 取消所有任务
fmt.Println("发送取消信号...")
cancel()
// 等待任务清理完成
time.Sleep(1 * time.Second)
// 2. 超时任务
fmt.Println("\n=== 超时任务 ===")
// 启动不同超时时间的任务
go taskWithTimeout(1, 1*time.Second) // 会超时
go taskWithTimeout(2, 3*time.Second) // 不会超时
time.Sleep(4 * time.Second)
// 3. 工作池模式
fmt.Println("\n=== 工作池模式 ===")
const numWorkers = 3
const numJobs = 10
jobs := make(chan Job, numJobs)
results := make(chan Result, numJobs)
var workerWg sync.WaitGroup
// 启动worker
for i := 1; i <= numWorkers; i++ {
workerWg.Add(1)
go worker2(i, jobs, results, &workerWg)
}
// 发送任务
go func() {
for i := 1; i <= numJobs; i++ {
jobs <- Job{
ID: i,
Data: fmt.Sprintf("任务数据-%d", i),
}
}
close(jobs)
}()
// 收集结果
go func() {
workerWg.Wait()
close(results)
}()
// 处理结果
for result := range results {
if result.Error != nil {
fmt.Printf("任务 %d 失败: %v\n", result.Job.ID, result.Error)
} else {
fmt.Printf("任务 %d 成功: %s\n", result.Job.ID, result.Output)
}
}
// 4. 生产者-消费者模式
fmt.Println("\n=== 生产者-消费者模式 ===")
data := make(chan int, 5) // 带缓冲的channel
var consumerWg sync.WaitGroup
// 启动消费者
for i := 1; i <= 2; i++ {
consumerWg.Add(1)
go consumer(i, data, &consumerWg)
}
// 启动生产者
go producer(data, 10)
// 等待所有消费者完成
consumerWg.Wait()
// 5. 错误处理和恢复
fmt.Println("\n=== 错误处理和恢复 ===")
var errorWg sync.WaitGroup
errors := make(chan error, 10)
// 启动多个可能出错的任务
for i := 1; i <= 5; i++ {
errorWg.Add(1)
go riskyTask(i, &errorWg, errors)
}
// 等待所有任务完成并关闭错误channel
go func() {
errorWg.Wait()
close(errors)
}()
// 收集和处理错误
var errorCount int
for err := range errors {
if err != nil {
fmt.Printf("收到错误: %v\n", err)
errorCount++
}
}
fmt.Printf("总共收到 %d 个错误\n", errorCount)
// 6. Goroutine泄漏检测
fmt.Println("\n=== Goroutine泄漏检测 ===")
before := runtime.NumGoroutine()
fmt.Printf("开始前goroutine数量: %d\n", before)
// 创建一些goroutine
var leakWg sync.WaitGroup
for i := 0; i < 10; i++ {
leakWg.Add(1)
go func(id int) {
defer leakWg.Done()
time.Sleep(100 * time.Millisecond)
}(i)
}
leakWg.Wait()
// 强制垃圾回收
runtime.GC()
time.Sleep(100 * time.Millisecond)
after := runtime.NumGoroutine()
fmt.Printf("结束后goroutine数量: %d\n", after)
if after > before {
fmt.Printf("可能存在goroutine泄漏: %d\n", after-before)
} else {
fmt.Println("没有检测到goroutine泄漏")
}
}
|