diff --git a/example-go-channel/Makefile b/example-go-channel/Makefile index c35c838..d74eec3 100644 --- a/example-go-channel/Makefile +++ b/example-go-channel/Makefile @@ -1,4 +1,6 @@ -build: +all: 5threads simple return-vals sendFunction + +5threads: GO111MODULE="off" go build -v -x -o ~/go/bin/5threads 5threads.go 5threads @@ -9,3 +11,7 @@ simple: return-vals: GO111MODULE="off" go build -v -x -o ~/go/bin/return-vals return-vals.go return-vals + +sendFunction: + GO111MODULE="off" go build -v -x -o ~/go/bin/sendFunction sendFunction.go + sendFunction diff --git a/example-go-channel/sendFunction.go b/example-go-channel/sendFunction.go new file mode 100644 index 0000000..1d1f8e0 --- /dev/null +++ b/example-go-channel/sendFunction.go @@ -0,0 +1,58 @@ +// 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! (ya, that was me and Etel) + +package main + +import ( + "fmt" + "sync" +) + +var wg sync.WaitGroup +var functionChan chan func (*sync.WaitGroup) + +type funcWait struct { + f func() + wgF sync.WaitGroup + err error + res int +} + + +func generateNumbers(total int, ch chan<- func (), wg *sync.WaitGroup) { + defer wg.Done() + + fmt.Printf("sending %d to channel\n", total) + ch <- func() { + fmt.Printf("inside f() sending %d to channel\n", total) + } +} + +func andlabsGoroutine(ch <-chan func(), wg *sync.WaitGroup) { + defer wg.Done() + + for f := range ch { + fmt.Printf("read f() from channel\n") + f() + } +} + +func main() { + functionChan = make(chan func(*sync.WaitGroup)) + + r := make(chan func() (int, error)) + res, err = (<-r)() + + wg.Add(1) + go andlabsGoroutine(functionChan, &wg) + + for idx := 1; idx <= total; idx++ { + generateNumbers(idx, functionChan, &wg) + } + + close(functionChan) + + fmt.Println("Waiting for goroutines to finish...") + wg.Wait() + fmt.Println("Done!") +} diff --git a/example-go-channel/simple-worker.go b/example-go-channel/simple-worker.go index 1b46818..2eac45d 100644 --- a/example-go-channel/simple-worker.go +++ b/example-go-channel/simple-worker.go @@ -29,5 +29,4 @@ func main() { } wg.Wait() - }