我为什么要使用`case

问题描述 投票:0回答:1

浏览一些代码,我发现了每秒执行某项操作的两种方式:

for {
    fmt.Println("This is printed every second")
    time.Sleep(time.Second * 1)
}

for {
    select {
    case <-time.After(time.Second * 1):
        fmt.Println("This is printed every second")
    }
}

除了第一个更具可读性(在我看来),我真的不了解一个相对于另一个的优势。有人知道吗?

loops go sleep
1个回答
1
投票

(至少有两个原因,您可能想要这样做:

  1. [time.Sleep总是阻止您当前的goroutine,如果您包含默认情况,则在通道上等待可能不会:]
    timeoutCh := time.After(time.Second)
LOOP:
    for {
        select {
        case <-timeoutCh:
            break LOOP
        default:
        }
        // do some work
    }
  1. 您可以使用它在长时间运行的操作上添加超时。假设您长期运行的操作会在频道上通知您。在这种情况下,将对该操作执行超时,如下所示:
    opNotifyCh := op()
    select {
    case res := <-opNotifyCh:
        fmt.Println("Op finished with result:", res)
    case <-time.After(time.Second):
        fmt.Println("Op timed out")
    }
  1. time.After给您一个channel。您可以使用它做任何您想做的事情-您可以将其传递给函数,可以将其返回给调用者,也可以将其放在结构中-确实可以。这给了您很多自由。
© www.soinside.com 2019 - 2024. All rights reserved.