73 lines
1.6 KiB
Go
73 lines
1.6 KiB
Go
// 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 (
|
|
"log"
|
|
"sync"
|
|
)
|
|
|
|
type funcWait struct {
|
|
f func()
|
|
wgF sync.WaitGroup
|
|
val int
|
|
err error
|
|
res int
|
|
}
|
|
|
|
var functionChan chan *funcWait
|
|
var afunc funcWait
|
|
var wg sync.WaitGroup
|
|
|
|
func generateNumbers(total int, ch chan<- *funcWait, af *funcWait) {
|
|
log.Println("generateNumbers() START total =", total)
|
|
ch <- af
|
|
log.Println("generateNumbers() END total =", total)
|
|
}
|
|
|
|
func andlabsGoroutine(ch <-chan *funcWait, wg *sync.WaitGroup) {
|
|
defer wg.Done()
|
|
|
|
log.Println("andlabsGoroutine() START")
|
|
for f := range ch {
|
|
log.Println("andlabsGoroutine() read f() from channel")
|
|
f.f()
|
|
f.wgF.Done()
|
|
}
|
|
log.Printf("andlabsGoroutine() END")
|
|
}
|
|
|
|
func main() {
|
|
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)
|
|
|
|
// afunc.wgF = wg
|
|
afunc.f = func() {
|
|
log.Println("\tGOT INSIDE: running f() from inside the structure & inside the wait group goroutine", afunc.val)
|
|
}
|
|
|
|
for idx := 1; idx <= 10; idx++ {
|
|
log.Println("START waitgroup idx =", idx)
|
|
afunc.val = idx * 20
|
|
afunc.wgF.Add(1)
|
|
generateNumbers(idx, functionChan, &afunc)
|
|
afunc.wgF.Wait()
|
|
log.Println("END waitgroup idx =", idx)
|
|
}
|
|
wg.Done()
|
|
|
|
close(functionChan)
|
|
// close(wg)
|
|
|
|
log.Println("Waiting for goroutines to finish...")
|
|
wg.Wait()
|
|
log.Println("Done!")
|
|
}
|