https://play.golang.org/p/bjuYMSq4lXZ
Trying to resolve the deadlock issue here, when printing out values.
Also how can i make it print values in order?
https://play.golang.org/p/bjuYMSq4lXZ
https://play.golang.org/p/nxW9y-exGSJ
It works when i dont use a waitGroup
Any reason why thats so?
https://play.golang.org/p/nxW9y-exGSJ
Some observations:
- pass
wg
toPrint
as an argument - don’t call
wg.Add(6)
, justwg.Add(1)
- let the goroutine that writes to
c
callclose(c)
- call
defer wg.Done()
at the start ofPrint
This works:
package main
import (
"fmt"
"sync"
)
func main() {
c := make(chan int)
a := []int{1, 3, 10, 8, 15, 23}
go func(i []int) {
for _, v := range i {
c <- v
}
close(c)
}(a)
var wg sync.WaitGroup
wg.Add(1)
go Print(c, &wg)
wg.Wait()
}
func Print(c chan int, wg *sync.WaitGroup) {
defer wg.Done()
for v := range c {
fmt.Println(v)
}
}
Thanks. Is there a way to make this version print in order without using channels? or thats what channels are solely fore
https://play.golang.org/p/USuv8dsdlfH
What do you mean by “print in order”? If you use range
on the slice a
, this will happen in the order of a
.
Print in order, as in the way it was made, i.e 1,3,10,8…
When i run the program, its usually printed randomly
The version I’ve included above writes the items of a
to c
in order. Print
reads from c
in the same order.
The last play you’ve linked to uses range
on a
and starts a new goroutine for every item in a
. The order of execution of these 6 goroutines is not deterministic. That’s why the result looks random. But this is not related to channels, is is the way go func
works.
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.