diff --git a/.gitignore b/.gitignore index a067d2e..2955ca5 100644 --- a/.gitignore +++ b/.gitignore @@ -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 diff --git a/example-go-channel/Makefile b/example-go-channel/Makefile new file mode 100644 index 0000000..bdb7f0e --- /dev/null +++ b/example-go-channel/Makefile @@ -0,0 +1,3 @@ +build: + GO111MODULE="off" go build -v -x + ./go-channels diff --git a/example-go-channel/main.go b/example-go-channel/main.go new file mode 100644 index 0000000..e19b132 --- /dev/null +++ b/example-go-channel/main.go @@ -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!") +}