How to print numbers in order using goroutine after all goroutines bing emited?
Here is the code which print numbers in random:
func main() {
var wg sync.WaitGroup
wg.Add(10)
for i := 1; i <= 10; i++ {
go func(i int) {
defer wg.Done()
fmt.Printf("i = %d\n", i)
}(i)
}
wg.Wait()
Emit goroutines in order to print numbers like below, it's not the solution I want.
func main() {
var wg sync.WaitGroup
for i := 1; i <= 10; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
fmt.Printf("i = %d\n", i)
}(i)
wg.Wait()
}
I want all goroutines being emited, and after then make them print numbers in order.
func main() {
wg.Add(10)
count := 10
cBegins := make([]chan interface{}, count)
for i := range cBegins {
cBegins[i] = make(chan interface{})
}
go func() {
cBegins[0] <- struct {}{}
}()
for i := 0; i < count; i++ {
go func(i int) {
defer wg.Done()
<-cBegins[i]
fmt.Printf("i = %d\n", i)
if i < 9 {
cBegins[i+1] <- struct {}{}
}
}(i)
}
wg.Wait()
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.