sub task pattern v1

This commit is contained in:
Jian Han 2018-01-06 02:32:19 +10:00
parent 3a128ec42d
commit 69d47635a9
2 changed files with 52 additions and 2 deletions

View File

@ -0,0 +1,33 @@
// Basic sends and receives on channels are blocking.
// However, we can use `select` with a `default` clause to
// implement _non-blocking_ sends, receives, and even
// non-blocking multi-way `select`s.
package main
import (
"fmt"
"time"
)
func main() {
ch1 := make(chan int)
ch2 := make(chan int)
go func(ch chan int) { <-ch }(ch1)
go func(ch chan int) { ch <- 2 }(ch2)
time.Sleep(time.Second)
for {
select {
case ch1 <- 1:
fmt.Println("Send operation on ch1 works!")
case test := <-ch2:
fmt.Println("Receive operation on ch2 works!", test)
default:
fmt.Println("Exit now!")
return
}
}
}

View File

@ -1,5 +1,7 @@
package main
import "github.com/davecgh/go-spew/spew"
// https://medium.com/capital-one-developers/buffered-channels-in-go-what-are-they-good-for-43703871828
// One common pattern for goroutines is fan-out. When you want to apply the same data to multiple algorithms,
@ -9,10 +11,25 @@ package main
// ideal way to gather the data back from your subtasks.
func main() {
evaluators := []Evaluator{google, yahoo, bing}
data := "Query"
r, e := DivideAndConquer(data, evaluators)
spew.Dump(r, e)
}
type Evaluator func(interface{}) (interface{}, error)
var google = func(data interface{}) (interface{}, error) {
return data, nil
}
var yahoo = func(data interface{}) (interface{}, error) {
return data, nil
}
var bing = func(data interface{}) (interface{}, error) {
return data, nil
}
type Evaluator func(data interface{}) (interface{}, error)
func DivideAndConquer(data interface{}, evaluators []Evaluator) ([]interface{}, []error) {
gather := make(chan interface{}, len(evaluators))