Should get all the values from the slice without getting a deadlock in the end. I dont get a deadlock error when i dont use waitGroups. <-time.After(time.Second) Is what i used instead of a waitGroup, and that helped
package main
import (
"fmt"
"sync"
)
var wg sync.WaitGroup
func main() {
c := make(chan int)
a := []int{1, 3, 10, 8, 15, 23}
wg.Add(len(a))
go func(i []int) {
for _, v := range i {
c <- v
}
}(a)
go Print(c)
wg.Wait()
}
func Print(c chan int) {
for v := range c {
fmt.Println(v)
}
wg.Done()
close(c)
}
you are confused about the synchronisation mechanism. The point is to synchronize the async workers. Not the number of elements they will process.
You are not closing the channel after writes has ended, but after reads are supposed to have ended. This is wrong.
You are making both the producer and the consumer async. It is a little weird. As you already have a thread in main, you can take advantage of it to not start a spurious routine.
some variations of your code after fixes
package main
import (
"fmt"
"sync"
)
var wg sync.WaitGroup
func main() {
c := make(chan int)
a := []int{1, 3, 10, 8, 15, 23}
wg.Add(1) // one async worker
go Print(c) // ensure the worker is started upfront
for _, v := range a {
c <- v // write the data
}
close(c) //then close
wg.Wait()
fmt.Println("done")
}
func Print(c chan int) {
for v := range c { // the loop will break because the channel is closed.
fmt.Println(v)
}
wg.Done()
}
You can also build it without any waitgroup.
package main
import (
"fmt"
)
func main() {
c := make(chan int)
a := []int{1, 3, 10, 8, 15, 23}
go func() {
for _, v := range a {
c <- v // write the data
}
close(c) //then close
}()
for v := range c { // the loop will break because the channel is closed.
fmt.Println(v)
}
fmt.Println("done")
}