golang-examples/example-go-channel/sendFunction.go

73 lines
1.6 KiB
Go
Raw Permalink Normal View History

2022-11-14 08:06:15 -06:00
// https://www.digitalocean.com/community/tutorials/how-to-run-multiple-functions-concurrently-in-go
// who came up with the idea of making community tutorials. that was a good idea! (ya, that was me and Etel)
package main
import (
2022-11-14 08:37:51 -06:00
"log"
2022-11-14 08:06:15 -06:00
"sync"
)
type funcWait struct {
f func()
wgF sync.WaitGroup
val int
2022-11-14 08:06:15 -06:00
err error
res int
}
2022-11-14 08:37:51 -06:00
var functionChan chan *funcWait
var afunc funcWait
var wg sync.WaitGroup
2022-11-14 08:06:15 -06:00
2022-11-14 08:37:51 -06:00
func generateNumbers(total int, ch chan<- *funcWait, af *funcWait) {
log.Println("generateNumbers() START total =", total)
ch <- af
log.Println("generateNumbers() END total =", total)
2022-11-14 08:06:15 -06:00
}
func andlabsGoroutine(ch <-chan *funcWait, wg *sync.WaitGroup) {
2022-11-14 08:06:15 -06:00
defer wg.Done()
2022-11-14 08:37:51 -06:00
log.Println("andlabsGoroutine() START")
2022-11-14 08:06:15 -06:00
for f := range ch {
2022-11-14 09:42:04 -06:00
log.Println("andlabsGoroutine() read f() from channel")
2022-11-14 08:37:51 -06:00
f.f()
f.wgF.Done()
2022-11-14 08:06:15 -06:00
}
2022-11-14 08:37:51 -06:00
log.Printf("andlabsGoroutine() END")
2022-11-14 08:06:15 -06:00
}
func main() {
2022-11-14 08:37:51 -06:00
functionChan = make(chan *funcWait)
// syntax to get the return values from a channel
// r := make(chan func() (int, error))
// afunc.res, afunc.err = (<-r)()
2022-11-14 08:06:15 -06:00
wg.Add(1)
go andlabsGoroutine(functionChan, &wg)
// afunc.wgF = wg
2022-11-14 08:37:51 -06:00
afunc.f = func() {
log.Println("\tGOT INSIDE: running f() from inside the structure & inside the wait group goroutine", afunc.val)
2022-11-14 08:37:51 -06:00
}
for idx := 1; idx <= 10; idx++ {
log.Println("START waitgroup idx =", idx)
afunc.val = idx * 20
afunc.wgF.Add(1)
2022-11-14 08:37:51 -06:00
generateNumbers(idx, functionChan, &afunc)
afunc.wgF.Wait()
log.Println("END waitgroup idx =", idx)
2022-11-14 08:06:15 -06:00
}
2022-11-14 09:42:04 -06:00
wg.Done()
2022-11-14 08:06:15 -06:00
close(functionChan)
2022-11-14 09:42:04 -06:00
// close(wg)
2022-11-14 08:06:15 -06:00
2022-11-14 08:37:51 -06:00
log.Println("Waiting for goroutines to finish...")
2022-11-14 08:06:15 -06:00
wg.Wait()
2022-11-14 08:37:51 -06:00
log.Println("Done!")
2022-11-14 08:06:15 -06:00
}