亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Golang:如何從循環外停止執行 for 循環?

Golang:如何從循環外停止執行 for 循環?

Go
慕絲7291255 2022-01-17 17:05:45
我正在使用帶有標簽的無限 for 循環。在 for 循環的范圍之外,我有一個計劃函數作為 go 例程運行。當滿足某個條件時,我想從預定函數中中斷 for 循環。我怎樣才能做到這一點?這就是我正在嘗試的,由于范圍問題,這顯然不起作用。package mainimport (  "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 回答

?
弒天下

TA貢獻1818條經驗 獲得超8個贊

建立一個信號通道。


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

當你想打破循環時關閉它。


go func (){

    for {

        fmt.Println("I will print every second", count)

        count++ 

        if count > 5 {

          close(quit)

          wg.Done()

          return

        }

        <-t.C

    }  

  }()

在關閉的通道上讀取立即返回零值(但在這種情況下我們不需要它)。否則從中讀取會阻塞并選擇將執行傳遞到“默認”情況。


 myLoop:

  for {

    select {

    case <- quit:

      break myLoop

    default:

      fmt.Println("iteration", i)

      i++

    }

  }


查看完整回答
反對 回復 2022-01-17
?
Smart貓小萌

TA貢獻1911條經驗 獲得超7個贊

Darigaaz 的答案適用于單個 goroutine,但關閉關閉的通道會出現恐慌(在這種情況下您也不需要等待組)。如果您有多個 goroutine,并且希望循環在所有這些都完成后退出,請使用具有更接近例程的等待組:


https://play.golang.org/p/RhmUzWhneT


package main


import (

    "fmt"

    "sync"

    "time"

)


func main() {

    var wg sync.WaitGroup

    quitCh := make(chan struct{})


    for i := 1; i <= 5; i++ {

        wg.Add(1)

        go func(i int) {

            count := 1

            t := time.NewTicker(time.Millisecond)

            for count <= 5 {

                fmt.Printf("Goroutine %v iteration %v\n", i, count)

                count++

                <-t.C

            }

            wg.Done()

        }(i)

    }


    // This is the closer routine.

    go func() {

        wg.Wait()

        close(quitCh)

    }()


    t := time.NewTicker(500 * time.Microsecond)

loop:

    for i := 1; ; i++ { // this is still infinite

        select {

        case <-quitCh:

            break loop // has to be named, because "break" applies to the select otherwise

        case <-t.C:

            fmt.Println("Main iteration", i)

        }

    }

    fmt.Println("End!")


}

作為命名循環樣式的替代方案,您可以在該選擇中使用fallthrough break:


    for i := 1; ; i++ { // this is still infinite

        select {

        case <-quitCh:

            // fallthrough

        case <-t.C:

            fmt.Println("Main iteration", i)

            continue

        }

        break // only reached if the quitCh case happens

    }


查看完整回答
反對 回復 2022-01-17
  • 2 回答
  • 0 關注
  • 489 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號