fix waitgroup

This commit is contained in:
Jeff Carr 2022-11-14 09:42:04 -06:00
parent f4d755db16
commit 9b57621ecd
3 changed files with 12 additions and 5 deletions

View File

@ -8,6 +8,10 @@ simple:
GO111MODULE="off" go build -v -x -o ~/go/bin/simple-worker simple-worker.go
simple-worker
main1:
GO111MODULE="off" go build -v -x -o ~/go/bin/main1 main.go
main1
return-vals:
GO111MODULE="off" go build -v -x -o ~/go/bin/return-vals return-vals.go
return-vals

View File

@ -12,21 +12,23 @@ func generateNumbers(total int, ch chan<- int, wg *sync.WaitGroup) {
defer wg.Done()
for idx := 1; idx <= total; idx++ {
fmt.Printf("START sending %d to channel\n", idx)
fmt.Printf("START generateNumbers() sending %d to channel\n", idx)
ch <- idx
// res, err := (<-r)()
fmt.Printf("END sending %d to channel\n", idx)
fmt.Printf("END generateNumbers() sending %d to channel\n", idx)
}
wg.Wait()
fmt.Printf("END wg sending to channel\n")
fmt.Printf("END generateNumbers() wg sending to channel\n")
}
func printInt(idx int, ch <-chan int, wg *sync.WaitGroup) {
defer wg.Done()
fmt.Printf("START printInt() for chan range\n")
for num := range ch {
fmt.Printf("%d: read %d from channel\n", idx, num)
}
fmt.Printf("START printInt() for chan range\n")
}
func main() {

View File

@ -21,7 +21,6 @@ var afunc funcWait
var wg sync.WaitGroup
func generateNumbers(total int, ch chan<- *funcWait, af *funcWait) {
defer wg.Done()
log.Println("generateNumbers() START total =", total)
ch <- af
@ -33,7 +32,7 @@ func andlabsGoroutine(ch <-chan *funcWait, wg *sync.WaitGroup) {
log.Println("andlabsGoroutine() START")
for f := range ch {
log.Println("read f() from channel")
log.Println("andlabsGoroutine() read f() from channel")
f.f()
}
log.Printf("andlabsGoroutine() END")
@ -58,8 +57,10 @@ func main() {
afunc.val = idx * 20
generateNumbers(idx, functionChan, &afunc)
}
wg.Done()
close(functionChan)
// close(wg)
log.Println("Waiting for goroutines to finish...")
wg.Wait()