3 回答

TA貢獻1801條經驗 獲得超8個贊
context.Context自從我從事 Go 工作以來已經有一段時間了,但我嘗試使用and讓它工作sync.Once。我還沒有測試過這個。
func keepConnUp(n netAddr, w chan<- io.Writer, err chan error) {
addr := fmt.Sprintf("%s:%d", n.Addr, n.Port)
done := make(chan bool)
ctx, cancel := context.WithCancel(context.Background())
cancel() // So that ctx.Err() returns non-nil on the first try
once := sync.Once{}
for {
<-err
if ctx.Err() != nil {
once.Do(func() {
conn, _ := net.Dial(n.Network, addr)
w <- conn
})
once = sync.Once{} // Reset once
ctx = context.WithTimeout(reconnectTimer) // Reset context timeout
}
}
}

TA貢獻1829條經驗 獲得超7個贊
type Conn struct {
conn net.Conn
dialing bool
mu sync.Mutex
}
func (c Conn) Dial() {
c.mu.Lock()
if c.dialing {
c.mu.Unlock()
return
}
c.dialing = true
c.mu.Unlock()
time.AfterFunc(reconnectTimer, func() {
c.conn, _ := net.Dial(n.Network, addr)
w <- c.conn
c.dialing = false
})
}
現在你可以調用Conn.Dial()一個 goroutine
- 3 回答
- 0 關注
- 144 瀏覽
添加回答
舉報