Created
June 10, 2021 15:23
-
-
Save luqmansen/298cc439fa6c5edbd1d0b8217fa9fb53 to your computer and use it in GitHub Desktop.
Exit a for loop using channel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.