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

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

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用