golfing 如何停掉channel
2021-03-07 本文已影响0人
本分撸码投资
- 通过close channel
- 通过发送消息机制
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)
}