more attempts at wait

This commit is contained in:
Jeff Carr 2022-11-14 08:37:51 -06:00
parent a2bd8f9c29
commit 741286521a
1 changed files with 27 additions and 19 deletions

View File

@ -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!")
}