ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
- > # 如何避免向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() } ```