控制2个groutine,2秒后取消,f1()1秒执行完 f2()3秒执行完

答案:

package main

import (
	"context"
	"fmt"
	"time"
)

func f1(execResult chan<- string) {
	// 模拟业务逻辑
	time.Sleep(time.Second * 1)
	execResult <- "f1"
}

func f2(execResult chan<- string) {
	// 模拟业务逻辑
	time.Sleep(time.Second * 3)
	execResult <- "f2"
}
func main() {
	stop1 := make(chan struct{},1)
	stop2 := make(chan struct{},1)
	ctx, _ := context.WithTimeout(context.Background(), time.Second*2)
	go func() {
		<-ctx.Done()
		stop1 <- struct{}{}
		stop2 <- struct{}{}
	}()
	go func() {
		execResult1 := make(chan string)
		go f1(execResult1)
		select {
		case <-stop1:
			fmt.Println("f1 超时")
			break
		case val := <-execResult1:
			fmt.Println(val)
		}
	}()
	go func() {
		execResult2 := make(chan string)
		go f2(execResult2)
		select {
		case <-stop2:
			fmt.Println("f2 超时")
		case val := <-execResult2:
			fmt.Println(val)
		}
	}()
	time.Sleep(time.Second * 10)
}