diff --git a/channel/noneblocking/main.go b/channel/noneblocking/main.go new file mode 100644 index 0000000..0f1ad7f --- /dev/null +++ b/channel/noneblocking/main.go @@ -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 + } + } +} diff --git a/concurrency/subtasks/main.go b/concurrency/subtasks/main.go index 868d338..9ff9289 100644 --- a/concurrency/subtasks/main.go +++ b/concurrency/subtasks/main.go @@ -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))