golang的协程不能像进程和线程那样可以采用某种手段强制退出,goroutinue应该主动退出

下面是goroutine主动退出的三种方法

1.使用for-range来管理

for range 能感知通道是否关闭    for str := range chandata {} 如果通道关闭则for range循环自动关闭   for循环结束 协程函数自动执行完毕  协程退出

go func(in <-chan int) {
    // Using for-range to exit goroutine
    // range has the ability to detect the close/end of a channel
    for x := range in {
        fmt.Printf("Process %d\n", x)
    }
}(inCh)

2.使用,ok来判断是否通道关闭

for {
    select {
        case v,ok := <-c :
            if ok {
                fmt.Println("通道没有关闭")
            } else {
                fmt.Println("通道关闭")
                return
            }
    }
    
}
// return直接结束协程函数

使用select的一个特征:select不会在nil的通道上进行等待 

for {
    select {
        case v,ok := <-c :
            if ok {
                fmt.Println("通道没有关闭")
            } else {
                c = nil
            }
        case v,ok := <-b :
            if ok {
                fmt.Println("通道没有关闭")
            } else {
                b = nil
            }
    }
    if c == nil && b == nil {
        return 
    }
}