51 lines
1.1 KiB
Go
51 lines
1.1 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!
|
|
|
|
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"sync"
|
|
)
|
|
|
|
func generateNumbers(total int, ch chan<- int, wg *sync.WaitGroup) {
|
|
defer wg.Done()
|
|
|
|
for idx := 1; idx <= total; idx++ {
|
|
fmt.Printf("START generateNumbers() sending %d to channel\n", idx)
|
|
ch <- idx
|
|
// res, err := (<-r)()
|
|
fmt.Printf("END generateNumbers() sending %d to channel\n", idx)
|
|
}
|
|
wg.Wait()
|
|
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() {
|
|
var wg sync.WaitGroup
|
|
numberChan := make(chan int)
|
|
|
|
for idx := 1; idx <= 2; idx++ {
|
|
wg.Add(1)
|
|
go printInt(idx, numberChan, &wg)
|
|
}
|
|
|
|
generateNumbers(10, numberChan, &wg)
|
|
|
|
close(numberChan)
|
|
|
|
fmt.Println("Waiting for goroutines to finish...")
|
|
wg.Wait()
|
|
fmt.Println("Done!")
|
|
}
|