I need to increase x
1000 times by creating 1000 goroutines which will increase the x
by one through channels. How would I do this?
package main
import (
"fmt"
)
func main() {
var ch = make(chan int)
//1000 goroutines sending 1 through a channel
var x = 0
for i := 0; i < 1000; i++ {
go func() {
ch <- 1
}()
}
//Here i need to increase x by value read from the channel and then stop when the last value was sent
//But this code doesn't work
for {
if v, ok := <-ch; ok {
x += v
} else {
break
}
}
fmt.Println(x)
}
I was thinking about closing the channel at the end but I don't know how to detect when the last value was sent
sync.WaitGroup
can be used for detecting the completion of a set of goroutines. For example:
package main
import (
"fmt"
"sync"
)
func main() {
var ch = make(chan int)
wg := &sync.WaitGroup{}
//1000 goroutines sending 1 through a channel
var x = 0
for i := 0; i < 1000; i++ {
wg.Add(1)
go func() {
defer wg.Done()
ch <- 1
}()
}
go func() {
wg.Wait()
close(ch)
}()
//Here i need to increase x by value read from the channel and then stop when the last value was sent
//But this code doesn't work
for {
if v, ok := <-ch; ok {
x += v
} else {
break
}
}
fmt.Println(x)
}