代码拉取完成,页面将自动刷新
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()
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。