Created
April 7, 2019 11:07
-
-
Save YiuTerran/f39064e3aa2152c64503a616725a65d9 to your computer and use it in GitHub Desktop.
golang顺序输出
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
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