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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
|
package main
import (
"context"
"fmt"
"sync"
"time"
)
// 1. 可取消的工作池
type CancellableWorkerPool struct {
workers int
jobs chan func(context.Context) error
results chan error
ctx context.Context
cancel context.CancelFunc
wg sync.WaitGroup
}
func NewCancellableWorkerPool(workers int) *CancellableWorkerPool {
ctx, cancel := context.WithCancel(context.Background())
return &CancellableWorkerPool{
workers: workers,
jobs: make(chan func(context.Context) error, 100),
results: make(chan error, 100),
ctx: ctx,
cancel: cancel,
}
}
func (p *CancellableWorkerPool) Start() {
for i := 0; i < p.workers; i++ {
p.wg.Add(1)
go p.worker(i)
}
}
func (p *CancellableWorkerPool) worker(id int) {
defer p.wg.Done()
for {
select {
case job, ok := <-p.jobs:
if !ok {
fmt.Printf("Worker %d 退出\n", id)
return
}
fmt.Printf("Worker %d 开始执行任务\n", id)
err := job(p.ctx)
select {
case p.results <- err:
case <-p.ctx.Done():
fmt.Printf("Worker %d 被取消\n", id)
return
}
case <-p.ctx.Done():
fmt.Printf("Worker %d 被取消\n", id)
return
}
}
}
func (p *CancellableWorkerPool) Submit(job func(context.Context) error) {
select {
case p.jobs <- job:
case <-p.ctx.Done():
fmt.Println("工作池已关闭,无法提交任务")
}
}
func (p *CancellableWorkerPool) Cancel() {
p.cancel()
}
func (p *CancellableWorkerPool) Close() {
close(p.jobs)
p.wg.Wait()
close(p.results)
}
func (p *CancellableWorkerPool) Results() <-chan error {
return p.results
}
// 2. HTTP客户端超时示例
func httpClientWithTimeout() {
fmt.Println("=== HTTP客户端超时示例 ===")
// 模拟HTTP请求函数
makeRequest := func(ctx context.Context, url string) error {
fmt.Printf("开始请求: %s\n", url)
// 模拟网络延迟
delay := 2 * time.Second
if url == "slow-api" {
delay = 5 * time.Second
}
select {
case <-time.After(delay):
fmt.Printf("请求完成: %s\n", url)
return nil
case <-ctx.Done():
fmt.Printf("请求被取消: %s, 原因: %v\n", url, ctx.Err())
return ctx.Err()
}
}
// 创建带超时的context
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
// 并发发起多个请求
urls := []string{"fast-api", "slow-api", "medium-api"}
var wg sync.WaitGroup
for _, url := range urls {
wg.Add(1)
go func(u string) {
defer wg.Done()
makeRequest(ctx, u)
}(url)
}
wg.Wait()
}
// 3. 数据库事务超时
func databaseTransactionTimeout() {
fmt.Println("\n=== 数据库事务超时 ===")
// 模拟数据库操作
executeQuery := func(ctx context.Context, query string, duration time.Duration) error {
fmt.Printf("执行查询: %s\n", query)
select {
case <-time.After(duration):
fmt.Printf("查询完成: %s\n", query)
return nil
case <-ctx.Done():
fmt.Printf("查询被取消: %s, 原因: %v\n", query, ctx.Err())
return ctx.Err()
}
}
// 模拟事务
runTransaction := func(ctx context.Context) error {
fmt.Println("开始事务")
// 执行多个查询
queries := []struct {
sql string
duration time.Duration
}{
{"SELECT * FROM users", 500 * time.Millisecond},
{"UPDATE users SET last_login = NOW()", 1 * time.Second},
{"INSERT INTO audit_log VALUES (...)", 2 * time.Second},
}
for _, q := range queries {
if err := executeQuery(ctx, q.sql, q.duration); err != nil {
fmt.Println("事务回滚")
return err
}
}
fmt.Println("事务提交")
return nil
}
// 设置事务超时
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
if err := runTransaction(ctx); err != nil {
fmt.Printf("事务失败: %v\n", err)
}
}
// 4. 级联取消示例
func cascadingCancellation() {
fmt.Println("\n=== 级联取消示例 ===")
// 父context
parentCtx, parentCancel := context.WithCancel(context.Background())
// 子context1
childCtx1, childCancel1 := context.WithCancel(parentCtx)
defer childCancel1()
// 子context2
childCtx2, childCancel2 := context.WithTimeout(parentCtx, 5*time.Second)
defer childCancel2()
// 孙context
grandChildCtx, grandChildCancel := context.WithCancel(childCtx1)
defer grandChildCancel()
// 启动监听各个context的goroutine
var wg sync.WaitGroup
contexts := []struct {
name string
ctx context.Context
}{
{"父context", parentCtx},
{"子context1", childCtx1},
{"子context2", childCtx2},
{"孙context", grandChildCtx},
}
for _, c := range contexts {
wg.Add(1)
go func(name string, ctx context.Context) {
defer wg.Done()
<-ctx.Done()
fmt.Printf("%s 被取消: %v\n", name, ctx.Err())
}(c.name, c.ctx)
}
// 2秒后取消父context
time.Sleep(2 * time.Second)
fmt.Println("取消父context...")
parentCancel()
wg.Wait()
}
// 5. Context与select的配合使用
func contextWithSelect() {
fmt.Println("\n=== Context与Select配合使用 ===")
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
// 数据channel
data := make(chan string, 1)
// 启动数据生产者
go func() {
time.Sleep(2 * time.Second)
data <- "重要数据"
}()
// 使用select等待数据或超时
select {
case result := <-data:
fmt.Printf("收到数据: %s\n", result)
case <-ctx.Done():
fmt.Printf("操作超时: %v\n", ctx.Err())
case <-time.After(1 * time.Second):
fmt.Println("1秒内没有收到数据,但继续等待...")
// 继续等待
select {
case result := <-data:
fmt.Printf("最终收到数据: %s\n", result)
case <-ctx.Done():
fmt.Printf("最终超时: %v\n", ctx.Err())
}
}
}
func main() {
// 1. 可取消的工作池示例
fmt.Println("=== 可取消的工作池 ===")
pool := NewCancellableWorkerPool(3)
pool.Start()
// 提交任务
for i := 1; i <= 10; i++ {
taskID := i
pool.Submit(func(ctx context.Context) error {
select {
case <-time.After(time.Duration(taskID*200) * time.Millisecond):
fmt.Printf("任务 %d 完成\n", taskID)
return nil
case <-ctx.Done():
fmt.Printf("任务 %d 被取消\n", taskID)
return ctx.Err()
}
})
}
// 2秒后取消所有任务
time.Sleep(2 * time.Second)
fmt.Println("取消所有任务...")
pool.Cancel()
// 收集结果
go func() {
for err := range pool.Results() {
if err != nil {
fmt.Printf("任务错误: %v\n", err)
}
}
}()
pool.Close()
httpClientWithTimeout()
databaseTransactionTimeout()
cascadingCancellation()
contextWithSelect()
}
|