dsyk33753 2016-06-09 15:01
浏览 330

Golang:如何从循环外部停止执行for循环?

I am using an infinite for loop with a label. Outside the scope of the for loop, I have a scheduled function running as a go routine. I want to break the for loop from the scheduled function when a certain condition is met. How can I accomplish the same ? This is what I am trying, which obviously won't work due to scope issue.

package main

import (
  "fmt"
  "time"
  "sync"
)

func main() {
  count := 0
  var wg sync.WaitGroup
  wg.Add(1)
  t := time.NewTicker(time.Second*1)

  go func (){
    for {
        fmt.Println("I will print every second", count)
        count++ 
        if count > 5 {
          break myLoop;
          wg.Done()
        }
        <-t.C
    }  
  }()

  i := 1

  myLoop:
  for {
    fmt.Println("iteration", i)
    i++
  }

  wg.Wait()
  fmt.Println("I will execute at the end")

}
  • 写回答

2条回答 默认 最新

  • doufen3091 2016-06-09 15:58
    关注

    Make a signalling channel.

    quit := make(chan struct{}{})
    

    Close it when you want to break a loop.

    go func (){
        for {
            fmt.Println("I will print every second", count)
            count++ 
            if count > 5 {
              close(quit)
              wg.Done()
              return
            }
            <-t.C
        }  
      }()
    

    Read on closed channel returns immediately with zero value (but we dont need it in this case). Otherwise reading from it blocks and select pass execution to "default" case.

     myLoop:
      for {
        select {
        case <- quit:
          break myLoop
        default:
          fmt.Println("iteration", i)
          i++
        }
      }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 chaquopy python 安卓
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题