阻止 goroutine 执行

我有一个功能如下:


func keepConnUp(n netAddr, w chan<- io.Writer, err chan error) {

    addr := fmt.Sprintf("%s:%d", n.Addr, n.Port)

    for {

        <-err

        time.Sleep(reconnectTimer)

        conn, _ := net.Dial(n.Network, addr)

        w <- conn

    }

}

目标是当我收到来自err chan. 但是,如果我已经在拨号或在某个时间段内,我不想重拨。但是,我可能会收到很多我不想阻止的错误。


我怎么能那样做?


编辑


到目前为止我已经实施的解决方案:


func keepConnUp(n netAddr, w chan<- io.Writer, err chan error) {

    addr := fmt.Sprintf("%s:%d", n.Addr, n.Port)

    done := make(chan bool)


    isDialing := false


    for {

        select {

        case <-err:

            if !isDialing {

                isDialing = true

                time.AfterFunc(reconnectTimer, func() {

                    done <- true

                })

                

            }

        case <-done:

            conn, _ := net.Dial(n.Network, addr)

            w <- conn

            isDialing = false

        }

    }

}


互换的青春
浏览 107回答 3
3回答

蝴蝶刀刀

context.Context自从我从事 Go 工作以来已经有一段时间了,但我尝试使用and让它工作sync.Once。我还没有测试过这个。func keepConnUp(n netAddr, w chan<- io.Writer, err chan error) {&nbsp; &nbsp; addr := fmt.Sprintf("%s:%d", n.Addr, n.Port)&nbsp; &nbsp; done := make(chan bool)&nbsp; &nbsp; ctx, cancel := context.WithCancel(context.Background())&nbsp; &nbsp; cancel() // So that ctx.Err() returns non-nil on the first try&nbsp; &nbsp; once := sync.Once{}&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; <-err&nbsp; &nbsp; &nbsp; &nbsp; if ctx.Err() != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; once.Do(func() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; conn, _ := net.Dial(n.Network, addr)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; w <- conn&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; once = sync.Once{} // Reset once&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ctx = context.WithTimeout(reconnectTimer) // Reset context timeout&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}

吃鸡游戏

type Conn struct {&nbsp; &nbsp; conn net.Conn&nbsp; &nbsp; dialing bool&nbsp; &nbsp; mu sync.Mutex}func (c Conn) Dial() {&nbsp; &nbsp; c.mu.Lock()&nbsp; &nbsp; if c.dialing {&nbsp; &nbsp; &nbsp; &nbsp; c.mu.Unlock()&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; }&nbsp; &nbsp; c.dialing = true&nbsp; &nbsp; c.mu.Unlock()&nbsp; &nbsp; time.AfterFunc(reconnectTimer, func() {&nbsp; &nbsp; &nbsp; &nbsp; c.conn, _ := net.Dial(n.Network, addr)&nbsp; &nbsp; &nbsp; &nbsp; w <- c.conn&nbsp; &nbsp; &nbsp; &nbsp; c.dialing = false&nbsp; &nbsp; })}现在你可以调用Conn.Dial()一个 goroutine

慕桂英546537

也许您可以使用sync.WaitGroup它来确保在错误后只有一次重拨呼叫。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go