Skip to content

Instantly share code, notes, and snippets.

@wqhyw
Created June 13, 2023 13:30
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 wqhyw/a162b9f1cc3ce6cba52680d4b1f4d404 to your computer and use it in GitHub Desktop.
Save wqhyw/a162b9f1cc3ce6cba52680d4b1f4d404 to your computer and use it in GitHub Desktop.
Print odd and even numbers alternately with two goroutines.
package main
func main() {
odd := make(chan int)
even := make(chan int)
// sub-routine print even number
go func() {
for i := <-even; i <= 10; i = <-even {
println("sub : ", i)
odd <- i + 1
}
}()
// start
go func() { odd <- 1 }()
// main-routine print odd number
for i := <-odd; i <= 10; i = <-odd {
println("main: ", i)
even <- i + 1
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment