美文网首页
golfing 如何停掉channel

golfing 如何停掉channel

作者: 本分撸码投资 | 来源:发表于2021-03-07 14:37 被阅读0次
  1. 通过close channel
  2. 通过发送消息机制
import (
    "fmt"
    "testing"
    "time"
)

func isCancelled(cancelChannel chan struct{}) bool {
    select {
        case <-cancelChannel:
            return true
        default:
            return false
    }
}
func cancel_1(cancelChannel chan struct{})  {
    cancelChannel <- struct{}{}
}
func cancel_2(cancelChannel chan struct{})  {
    close(cancelChannel)
}
func TestCancle(t *testing.T) {
    cancelChan := make(chan struct{},0)
    for i := 0; i < 5; i++ {
        go func(i int, canchelCh chan struct{}) {
            for  {
                if isCancelled(cancelChan) {
                    break
                }
                time.Sleep(time.Microsecond * 50)
            }
            fmt.Println(i,"Done")
        }(i, cancelChan)
    }
    cancel_2(cancelChan)
    time.Sleep(time.Second*1)
}

相关文章

网友评论

      本文标题:golfing 如何停掉channel

      本文链接:https://www.haomeiwen.com/subject/rthyqltx.html