Main {
go routine_1(carryout a time consuming task and return output)
go routine_2(wait for output from routine_1, collect output and do task_2)
go routine_3(wait for output from routine_1, collect output and do task_3)
wait for all routines to complete
}
I have used channel, but once routine_2 reads the data routine_3 doesn't get the data.
I dont want the main thread to do the syncronization i.e to know the dependencies between routine_2,routine_3 to routine_1
Turns out closing the channel will give the needed broadcast for the other routines to know the result is ready.
Thank you for your time.(This is my first question in stackoverflow, really happy to see such good quality and quick responses) Thanks to all of you.
Updating with the answer that I picked. thanks again.
package main
import (
"fmt"
"sync"
)
func computeResult() int {
return 100
}
func main() {
var wg sync.WaitGroup
wg.Add(2)
var output int
ch := make(chan struct{})
// Compute result
go func() {
defer wg.Done()
output = computeResult()
fmt.Println("closing channel to signal task done")
close(ch)
fmt.Println("channel closed")
}()
go func() {
defer wg.Done()
// Wait for ch close
<-ch
fmt.Println(output)
}()
wg.Wait()
var wg2 sync.WaitGroup
wg2.Add(1)
go func() {
defer wg2.Done()
fmt.Println("wait on closed channel")
// Wait for ch close
<-ch
fmt.Println(output)
}()
wg2.Wait()
}
routine_2androutine_3, and send the same output to both.