通过channel的方式
func TestChannelStop(t *testing.T) {
stop := make(chan bool)
go func() {
for{
select {
case <-stop:
fmt.Println("结束")
return
default:
fmt.Println("运行中")
time.Sleep(time.Second)
}
}
}()
time.Sleep(5*time.Second)
stop<-true
time.Sleep(2*time.Second)
}
通过sync.WaitGroup 的方式
func TestWaitGroup(t *testing.T) {
wg := sync.WaitGroup{}
wg.Add(2)
test := func(i int,timeout int) {
fmt.Printf("doSomething(%d)...",i)
fmt.Println()
time.Sleep(time.Duration(timeout)*time.Second)
wg.Done()
time.Sleep(time.Duration(timeout)*time.Second)
fmt.Printf("该段内容不会被输出(%d)... ",i)
fmt.Println()
}
go test(1,5)
go test(2,5)
wg.Wait()
}
通过context.Context的方式
const GOROUTINE_KEY = "goroutine_key"
func watch(ctx context.Context,key string){
goroutineKey := ctx.Value(GOROUTINE_KEY)
if goroutineKey == nil{
goroutineKey = key
}
keyStr := "go"+goroutineKey.(string)
for{
select {
case <-ctx.Done():
fmt.Println(keyStr +"结束")
return
default:
fmt.Println(keyStr+"运行中..")
time.Sleep(time.Second)
}
}
}
/**
通过手动执行cancel函数的方式
这个cancel函数是创建Context时返回的
*/
func TestContextStop(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
go watch(ctx,"1")
go watch(ctx,"2")
go watch(ctx,"3")
time.Sleep(5*time.Second)
cancel()
time.Sleep(2*time.Second)
}
/**
通过指定结束时间的方式自动结束
*/
func TestContextStop1(t *testing.T) {
now := time.Now()
next := now.Add(5*time.Second)
ctx, _ := context.WithDeadline(context.Background(),next)
go watch(ctx,"1")
go watch(ctx,"2")
go watch(ctx,"3")
time.Sleep(7*time.Second)
}
/**
通过设置超时时间结束
*/
func TestContextStop2(t *testing.T){
ctx,_ := context.WithTimeout(context.Background(),5*time.Second)
valueCtx := context.WithValue(ctx,GOROUTINE_KEY,"1")
go watch(valueCtx,"2")
time.Sleep(7*time.Second)
}
文章转载自一把尺子,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




