context.WithCancel
returns two associated objects, CTX and cancel, cancel call to send a null struct ctx, ctx once receiving the object to terminate the execution goroutine;
CTX is thread safe, it can be simultaneously transmitted to the plurality goroutine, triggering cancel, cancel the execution of all goroutine
package main import ( "context" "fmt" "time" ) func testContext(){ ctx,cancel := context.WithCancel(context.Background()) go d1(ctx) go d2(ctx) time.Sleep(7*time.Second) cancel() } func d1(ctx context.Context){ i:=0 for { time.Sleep(1*time.Second) i++ select { case <- ctx.Done(): fmt.Println("d1 over") return default: fmt.Println("d1 ",i) } } } func d2(ctx context.Context){ fmt.Println("d2 start") <- ctx.Done() fmt.Println("d2 over") } func main(){ testContext() fmt.Println("main over") }
Export
d2 start d1 1 d1 2 d1 3 d1 4 d1 5 d1 6 main over