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

49 lines
1005 B
Go
Raw Normal View History

2022-11-13 13:30:01 -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!
package main
import (
"fmt"
"sync"
)
func generateNumbers(total int, ch chan<- int, wg *sync.WaitGroup) {
defer wg.Done()
for idx := 1; idx <= total; idx++ {
2022-11-13 14:19:18 -06:00
fmt.Printf("START sending %d to channel\n", idx)
2022-11-13 13:30:01 -06:00
ch <- idx
2022-11-13 14:55:38 -06:00
// res, err := (<-r)()
2022-11-13 14:19:18 -06:00
fmt.Printf("END sending %d to channel\n", idx)
2022-11-13 13:30:01 -06:00
}
2022-11-13 14:19:18 -06:00
wg.Wait()
fmt.Printf("END wg sending to channel\n")
2022-11-13 13:30:01 -06:00
}
func printInt(idx int, ch <-chan int, wg *sync.WaitGroup) {
defer wg.Done()
for num := range ch {
fmt.Printf("%d: read %d from channel\n", idx, num)
}
}
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!")
}