Created
June 13, 2023 13:30
-
-
Save wqhyw/a162b9f1cc3ce6cba52680d4b1f4d404 to your computer and use it in GitHub Desktop.
Print odd and even numbers alternately with two goroutines.
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 | |
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