go channel example
This commit is contained in:
parent
33f6e47c66
commit
986034cdcf
|
@ -10,6 +10,7 @@ example-ssh/ssh-ed25519
|
|||
example-ssh/with-passwd
|
||||
|
||||
example-expect/example-expect
|
||||
example-go-channel/example-go-channel
|
||||
example-gocui-active/example-gocui-active
|
||||
example-gocui-colorstrue/example-gocui-colorstrue
|
||||
example-gocui-dynamic/example-gocui-dynamic
|
||||
|
@ -25,3 +26,5 @@ example-ui-radiobutton/example-ui-radiobutton
|
|||
example-ui-splash/example-ui-splash
|
||||
example-ui-table/example-ui-table
|
||||
|
||||
autobuild/autobuild
|
||||
example-flag/example-flag
|
||||
|
|
|
@ -0,0 +1,3 @@
|
|||
build:
|
||||
GO111MODULE="off" go build -v -x
|
||||
./go-channels
|
|
@ -0,0 +1,44 @@
|
|||
// 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!")
|
||||
}
|
Loading…
Reference in New Issue