Last active
July 10, 2024 00:24
-
-
Save ytxmobile98/23d240fd93dc03e2e8bf0d190d92349e to your computer and use it in GitHub Desktop.
Go use goroutines to print 1~10
This file contains hidden or 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 printN(n int, prev <-chan struct{}, next chan<- struct{}) { | |
| <-prev // wait for the previous signal | |
| println(n) | |
| next <- struct{}{} // activate the next goroutine | |
| } | |
| func printAll(n int) { | |
| if n < 1 { | |
| return | |
| } | |
| channels := make([]chan struct{}, n) | |
| for i := range channels { | |
| channels[i] = make(chan struct{}) | |
| } | |
| for i := 1; i <= n; i++ { | |
| prev := channels[i-1] | |
| next := channels[i%n] | |
| go printN(i, prev, next) | |
| } | |
| channels[0] <- struct{}{} // send the start signal | |
| <-channels[0] // wait for the finishing signal | |
| } | |
| func main() { | |
| // use goroutines to print 1~10 | |
| printAll(10) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment