From 741286521a277a6dd5c101f1b726d2933f916cee Mon Sep 17 00:00:00 2001 From: Jeff Carr Date: Mon, 14 Nov 2022 08:37:51 -0600 Subject: [PATCH] more attempts at wait --- example-go-channel/sendFunction.go | 46 ++++++++++++++++++------------ 1 file changed, 27 insertions(+), 19 deletions(-) diff --git a/example-go-channel/sendFunction.go b/example-go-channel/sendFunction.go index 1d1f8e0..9f6e43f 100644 --- a/example-go-channel/sendFunction.go +++ b/example-go-channel/sendFunction.go @@ -4,13 +4,10 @@ package main import ( - "fmt" + "log" "sync" ) -var wg sync.WaitGroup -var functionChan chan func (*sync.WaitGroup) - type funcWait struct { f func() wgF sync.WaitGroup @@ -18,41 +15,52 @@ type funcWait struct { res int } +var functionChan chan *funcWait +var afunc funcWait +var wg sync.WaitGroup -func generateNumbers(total int, ch chan<- func (), wg *sync.WaitGroup) { +func generateNumbers(total int, ch chan<- *funcWait, af *funcWait) { defer wg.Done() - fmt.Printf("sending %d to channel\n", total) - ch <- func() { - fmt.Printf("inside f() sending %d to channel\n", total) - } + log.Println("generateNumbers() START total =", total) + ch <- af + log.Println("generateNumbers() END total =", total) } -func andlabsGoroutine(ch <-chan func(), wg *sync.WaitGroup) { +func andlabsGoroutine(ch <-chan *funcWait, wgF *sync.WaitGroup) { defer wg.Done() + log.Println("andlabsGoroutine() START") for f := range ch { - fmt.Printf("read f() from channel\n") - f() + log.Println("read f() from channel") + f.f() } + log.Printf("andlabsGoroutine() END") } func main() { - functionChan = make(chan func(*sync.WaitGroup)) - r := make(chan func() (int, error)) - res, err = (<-r)() + functionChan = make(chan *funcWait) + + // syntax to get the return values from a channel +// r := make(chan func() (int, error)) +// afunc.res, afunc.err = (<-r)() wg.Add(1) go andlabsGoroutine(functionChan, &wg) - for idx := 1; idx <= total; idx++ { - generateNumbers(idx, functionChan, &wg) + afunc.wgF = wg + afunc.f = func() { + log.Println("\tGOT INSIDE: running f() from inside the structure & inside the wait group goroutine") + } + + for idx := 1; idx <= 10; idx++ { + generateNumbers(idx, functionChan, &afunc) } close(functionChan) - fmt.Println("Waiting for goroutines to finish...") + log.Println("Waiting for goroutines to finish...") wg.Wait() - fmt.Println("Done!") + log.Println("Done!") }