🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
- > # 如何避免向close 发送 - 使用互斥锁保护 `channel` 的状态 ``` package main import ( "fmt" "sync" ) type SafeChannel struct { ch chan int closed bool mu sync.RWMutex } func NewSafeChannel() *SafeChannel { return &SafeChannel{ ch: make(chan int), } } func (sc *SafeChannel) Send(value int) bool { sc.mu.RLock() defer sc.mu.RUnlock() if sc.closed { return false } sc.ch <- value return true } func (sc *SafeChannel) Close() { sc.mu.Lock() defer sc.mu.Unlock() if !sc.closed { close(sc.ch) sc.closed = true } } func main() { safeCh := NewSafeChannel() go func() { for i := 0; i < 5; i++ { if ok := safeCh.Send(i); !ok { fmt.Println("Failed to send, channel is closed") } } }() // Simulate some work, then close the channel safeCh.Close() } ```