golang一段函数超时代码,超时的话如何结束当前的并发进程,并且重新运行函数

package main
import "time"
import "fmt"
import "runtime"
func a() {
    c1 := make(chan string, 1)
    go func() {
        time.Sleep(time.Second * 2)
        c1 <- "result 1"
    }()
    select {
    case res := <-c1:
        fmt.Println(res)
    case <-time.After(time.Second * 1):
        //超时的话如何结束当前的并发进程,并且重新运行a函数
        runtime.Goexit()
        fmt.Println("timeout 1")
    }
}
func b() {
    c1 := make(chan string, 1)
    go func() {
        time.Sleep(time.Second * 2)
        c1 <- "result 1"
    }()
    select {
    case res := <-c1:
        fmt.Println(res)
    case <-time.After(time.Second * 1):
        //超时的话如何结束当前的并发进程,并且重新运行a函数
        //这样写发现进程越来越多
        go b();
        runtime.Goexit()
    }
}
func main() {
    go a()
    b()
}
// todo: cancellation

如果超时,让goroutine直接通过channel返回超时错误就可以;然后外部程序再重新执行goroutine。

package main
import (
    "errors"
    "time"
    "fmt"
)
func work(in chan int, out chan error) {
    select {
    case <-time.After(time.Second):
        out <- errors.New("timeout")
    case n := <-in:
        fmt.Printf("receive %d\n", n)
        out <- nil
    }
}
func main() {
    in := make(chan int, 10)
    out := make(chan error, 1)
    for i := 0; i < 3; i++ {
        go work(in, out)
        if err := <-out; err != nil {
            fmt.Println(err)
        }
    }
    in <- 1234
    go work(in, out)
    fmt.Println(<-out)
}
文档更新时间: 2019-06-07 10:12   作者:月影鹏鹏