Skip to content

Instantly share code, notes, and snippets.

@ytxmobile98
Last active July 10, 2024 00:24
Show Gist options
  • Select an option

  • Save ytxmobile98/23d240fd93dc03e2e8bf0d190d92349e to your computer and use it in GitHub Desktop.

Select an option

Save ytxmobile98/23d240fd93dc03e2e8bf0d190d92349e to your computer and use it in GitHub Desktop.
Go use goroutines to print 1~10
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