more channel tests
This commit is contained in:
parent
a9779a3f8c
commit
a2bd8f9c29
|
@ -1,4 +1,6 @@
|
||||||
build:
|
all: 5threads simple return-vals sendFunction
|
||||||
|
|
||||||
|
5threads:
|
||||||
GO111MODULE="off" go build -v -x -o ~/go/bin/5threads 5threads.go
|
GO111MODULE="off" go build -v -x -o ~/go/bin/5threads 5threads.go
|
||||||
5threads
|
5threads
|
||||||
|
|
||||||
|
@ -9,3 +11,7 @@ simple:
|
||||||
return-vals:
|
return-vals:
|
||||||
GO111MODULE="off" go build -v -x -o ~/go/bin/return-vals return-vals.go
|
GO111MODULE="off" go build -v -x -o ~/go/bin/return-vals return-vals.go
|
||||||
return-vals
|
return-vals
|
||||||
|
|
||||||
|
sendFunction:
|
||||||
|
GO111MODULE="off" go build -v -x -o ~/go/bin/sendFunction sendFunction.go
|
||||||
|
sendFunction
|
||||||
|
|
|
@ -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!")
|
||||||
|
}
|
|
@ -29,5 +29,4 @@ func main() {
|
||||||
}
|
}
|
||||||
|
|
||||||
wg.Wait()
|
wg.Wait()
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue