61 Star 341 Fork 416

infraboard / go-course

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
exit.go 1.36 KB
一键复制 编辑 原始数据 按行查看 历史
Mr.Yu 提交于 2021-08-08 18:53 . 更新课件
package tips
import (
"context"
"fmt"
"sync"
"time"
)
func worker(cannel chan struct{}) {
for {
select {
default:
fmt.Println("hello")
time.Sleep(100 * time.Millisecond)
case <-cannel:
// 退出
return
}
}
}
func CancelWithChannel() {
cancel := make(chan struct{})
go worker(cancel)
time.Sleep(time.Second)
cancel <- struct{}{}
}
func workerv2(wg *sync.WaitGroup, cancel chan bool) {
defer wg.Done()
for {
select {
default:
fmt.Println("hello")
time.Sleep(100 * time.Millisecond)
case <-cancel:
// 清理工作需要进行
return
}
}
}
func CancelWithDown() {
cancel := make(chan bool)
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go workerv2(&wg, cancel)
}
time.Sleep(time.Second)
// 发送退出信号
close(cancel)
// 等待goroutine 安全退出
wg.Wait()
}
func workerV3(ctx context.Context, wg *sync.WaitGroup) error {
defer wg.Done()
for {
select {
default:
fmt.Println("hello")
time.Sleep(100 * time.Millisecond)
case <-ctx.Done():
return ctx.Err()
}
}
}
func CancelWithCtx() {
start := time.Now()
defer func() {
fmt.Print(time.Since(start).Seconds())
}()
// 控制超时
ctx, _ := context.WithTimeout(context.Background(), 2*time.Second)
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go workerV3(ctx, &wg)
}
// 等待安全退出
wg.Wait()
}
Go
1
https://gitee.com/infraboard/go-course.git
git@gitee.com:infraboard/go-course.git
infraboard
go-course
go-course
d5aecf891a93

搜索帮助