Click here to Skip to main content
15,886,830 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
This abstract code will display "true" in a loop as long as channel receives new messages.
golang
package main

import (
	"fmt"
	"sync"
)

var a = make(chan bool)
var wg sync.WaitGroup

func main() {
	wg.Add(1)
	go test()
	for i := 0; i < 2; i++ {
		wg.Add(1)
		go test2()
	}
	wg.Wait()
}

func test() {
	for val := range a {
		fmt.Println(val)
	}
	wg.Done()
}

func test2() {
	for i := 0; i < 3; i++ {
		a <- true
	}
	wg.Done()
}


What I have tried:

The problem is that WaitGroups do not synchronize it as advertised. Despite channel being unused at the end wg.Done() is never called, and application ends with a deadlock. I also can't close the channel, because multiple test2 functions access the same channel.
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900