企业🤖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() } ```