package main import ( "context" "fmt" "time" "runtime" ) func test ( ctx context . Context , cancelFunc func ()) { var i int for { select { case - ctx . Done (): fmt . Println ( "test done...." ) return default : fmt . Printf ( "执行第%d次
import (
"context"
"fmt"
"time"
"runtime"
)
func test(ctx context.Context,cancelFunc func()) {
var i int
for {
select {
case <-ctx.Done():
fmt.Println("test done....")
return
default:
fmt.Printf("执行第%d次go程\n",i)
if i == 7{
cancelFunc()
fmt.Println("9999999999")
return
}
i++
time.Sleep(time.Second)
}
}
fmt.Println("go程执行完毕!")
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
go test(ctx,cancel)
go func(context.Context) {
ticker := time.NewTicker(1 * time.Second)
for {
select {
case <-ctx.Done():
fmt.Println("done....")
return
case <-ticker.C:
fmt.Println("------aaaaaaaa-------")
time.Sleep(time.Second)
fmt.Println("------go程结束--------------")
}
}
runtime.Goexit()
}(ctx)
time.Sleep(20*time.Second)
fmt.Println("-----333333333-----")
//for{
// runtime.GC()
//}
}