SoFunction
Updated on 2025-03-05

Golang implements a method to automatically exit after the for loop run timeout

Preface

The for loop is used to iterate over an array or number. When using for loop to traverse strings, there are also two ways: byte and rune. The first is byte and the second is rune. I won’t say much about it below, let’s take a look at the detailed introduction together.

Golang implements a for loop

package main

import "fmt"

func main() {
  sum := 0
  for i := 0; i < 10; i++ {
    sum += i
  }
  (sum)
}

Just like in C, pre- and post-statements can be empty.

package main

import "fmt"

func main() {
  sum := 1
  for ; sum < 1000; {
    sum += sum
  }
  (sum)
}

Based on this, semicolons can be omitted:

package main

import "fmt"

func main() {
  sum := 1
  for sum < 1000 {
    sum += sum
  }
  (sum)
}

If the loop condition is omitted, it is a source of the dead loop.

package main

func main() {
  for ; ; {
  }
}

In order to avoid burdens, semicolons can be omitted, so a dead loop can be expressed concisely.

package main

func main() {
  for {
  }
}

For loop timeout automatically exits

How to control the for loop to automatically exit after a period of timeout? The idea is very simple, which is to use select to listen to the channel in the for loop. The code is as follows:

package main
 
import (
 "fmt"
 "time"
)
 
func main() {
 timeout := ( * 10)
 finish := make(chan bool)
 count := 1
 go func() {
 for {
 select {
 case <-timeout:
 ("timeout")
 finish <- true
 return
 default:
 ("haha %d\n", count)
 count++
 }
 ( * 1)
 }
 }()
 
 <-finish
 
 ("Finish")
}

Here is a timeout for loop for 10s.

Run content:

haha 1
haha 2
haha 3
haha 4
haha 5
haha 6
haha 7
haha 8
haha 9
haha 10
timeout
Finish

Summarize

The above is the entire content of this article. I hope that the content of this article has certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.