1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | package main import ( "context" "fmt" "time" ) func main() { busyChan := make( chan bool) ctx, cancel := context.WithCancel(context.Background()) go func (ctx context.Context) { for { select { case <-busyChan: fmt.Println( "Pretending to be very busy" ) time.Sleep(5000 * time.Second) case <-ctx.Done(): return } } }(ctx) busyChan <- true fmt.Println( "Doing some other things" ) time.Sleep(3 * time.Second) fmt.Println( "Stopping the goroutine" ) cancel() } |
Prentending to be very busy Doing some other things Stopping the goroutine