Skip to content

Instantly share code, notes, and snippets.

@luqmansen
Created June 10, 2021 15:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luqmansen/298cc439fa6c5edbd1d0b8217fa9fb53 to your computer and use it in GitHub Desktop.
Save luqmansen/298cc439fa6c5edbd1d0b8217fa9fb53 to your computer and use it in GitHub Desktop.
Exit a for loop using channel
package main
import (
"fmt"
"time"
)
func main() {
function2()
for {
fmt.Println("this is main function")
time.Sleep(1 * time.Second)
}
}
func function2() {
function3()
fmt.Println("function2 exit")
}
func function3() {
q := make(chan bool)
go func() {
for {
select {
case <-q:
fmt.Println("EXIT")
return
default:
fmt.Println("yeet")
time.Sleep(1 * time.Second)
}
}
}()
go func() {
for {
select {
case <-q:
fmt.Println("EXIT 2")
return
default:
fmt.Println("yeet 2")
time.Sleep(2 * time.Second)
}
}
}()
time.Sleep(5 * time.Second)
fmt.Println("closing channel q")
close(q)
return
}
@luqmansen
Copy link
Author

luqmansen commented Jun 10, 2021

It took me time to realize that goroutine exit when the MAIN function exit, not the CALLER function exit. In this example, I had a goroutine that running an infinite for loop, with for loop. select could achieve the same behavior while also I can trigger it to exit by using channel.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment