more examples

This commit is contained in:
Jeff Carr 2022-11-13 14:19:18 -06:00
parent 986034cdcf
commit 15efa4258e
4 changed files with 87 additions and 3 deletions

View File

@ -0,0 +1,45 @@
// 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 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 <= 5; idx++ {
fmt.Printf("START printInt %d\n", idx)
wg.Add(1)
go printInt(idx, numberChan, &wg)
}
generateNumbers(20, numberChan, &wg)
close(numberChan)
fmt.Println("Waiting for goroutines to finish...")
wg.Wait()
fmt.Println("Done!")
}

View File

@ -1,3 +1,6 @@
build:
GO111MODULE="off" go build -v -x
./go-channels
GO111MODULE="off" go build -v -x -o ~/go/bin/5threads 5threads.go
5threads
simple:
GO111MODULE="off" go build -v -x -o ~/go/bin/simple-worker simple-worker.go

View File

@ -12,9 +12,12 @@ 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)
fmt.Printf("START sending %d to channel\n", idx)
ch <- idx
fmt.Printf("END sending %d to channel\n", idx)
}
wg.Wait()
fmt.Printf("END wg sending to channel\n")
}
func printInt(idx int, ch <-chan int, wg *sync.WaitGroup) {

View File

@ -0,0 +1,33 @@
package main
import (
"fmt"
"sync"
"time"
)
func worker(id int) {
fmt.Printf("Worker %d starting\n", id)
time.Sleep(time.Second)
fmt.Printf("Worker %d done\n", id)
}
func main() {
var wg sync.WaitGroup
for i := 1; i <= 5; i++ {
wg.Add(1)
i := i
go func() {
defer wg.Done()
worker(i)
}()
}
wg.Wait()
}