Skip to content

Instantly share code, notes, and snippets.

@YiuTerran
Created April 7, 2019 11:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YiuTerran/f39064e3aa2152c64503a616725a65d9 to your computer and use it in GitHub Desktop.
Save YiuTerran/f39064e3aa2152c64503a616725a65d9 to your computer and use it in GitHub Desktop.
golang顺序输出
import (
"fmt"
"sync/atomic"
)
const (
total = 30
threads = 3
)
var (
counter int32
done = make(chan struct{})
)
func main() {
var chns [threads]chan struct{}
for i := 0; i < threads; i++ {
chns[i] = make(chan struct{})
}
var next chan struct{}
for i := 0; i < threads; i++ {
if i == threads-1 {
next = chns[0]
} else {
next = chns[i+1]
}
go func(mine, next chan struct{}, toPrint string) {
for {
<-mine
fmt.Println(toPrint)
if atomic.AddInt32(&counter, 1) == total {
close(done)
return
}
next <- struct{}{}
}
}(chns[i], next, string([]byte{'A' + byte(i)}))
}
chns[0] <- struct{}{}
<-done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment