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

45 lines
871 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++ {
fmt.Printf("sending %d to channel\n", idx)
ch <- idx
}
}
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!")
}