drgm51600 2019-08-28 16:47
浏览 107
已采纳

即使经过很短的时间,Go程序也会永远休眠。

I'm trying to build some short of semaphore in Go. Although when when the channel receives the signal it just sleeps forever.

I've tried changing the way to sleep and the duration to sleep, but it stills just stopping forever.

Here a representation of what I've tried:

func main() {
    backOffChan := make(chan struct{})
    go func() {
        time.Sleep(2)
        backOffChan <- struct{}{}
    }()
    for {
        select {
        case <-backOffChan:
            d := time.Duration(5 * time.Second)
            log.Println("reconnecting in %s", d)
            select {
            case <-time.After(d):
                log.Println("reconnected after %s", d)
                return
            }
        default:
        }
    }
}

I expect that it just returns after printing the log message and returning.

Thanks!

  • 写回答

1条回答 默认 最新

  • duanchen7703 2019-08-28 17:01
    关注

    This code has a number of problems, mainly a tight loop using for/select that may not allow the other goroutine to ever get to send on the channel. Since the default case is empty and the select has only one case, the whole select is unnecessary. The following code works correctly:

    backOffChan := make(chan struct{})
    go func() {
        time.Sleep(1 * time.Millisecond)
        backOffChan <- struct{}{}
    }()
    for range backOffChan {
        d := time.Duration(10 * time.Millisecond)
        log.Printf("reconnecting in %s", d)
        select {
        case <-time.After(d):
            log.Printf("reconnected after %s", d)
            return
        }
    }
    

    This will wait until the backOffChan gets a message without burning a tight loop.

    (Note that this code also addresses issues using log.Println with formatting directives - these were corrected to log.Printf).

    See it in action here: https://play.golang.org/p/ksAzOq5ekrm

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备