Resolve deadlock error

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

2 Likes

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

2 Likes

Some observations:

  • pass wg to Print as an argument
  • don’t call wg.Add(6), just wg.Add(1)
  • let the goroutine that writes to c call close(c)
  • call defer wg.Done() at the start of Print

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)
	}
}

https://play.golang.org/p/RYW2WbzJbtJ

3 Likes

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

2 Likes

What do you mean by “print in order”? If you use range on the slice a, this will happen in the order of a.

2 Likes

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

2 Likes

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.

3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.