diff --git a/concurrency/fan/main.go b/concurrency/fan/main.go new file mode 100644 index 0000000..8e30f05 --- /dev/null +++ b/concurrency/fan/main.go @@ -0,0 +1,62 @@ +package main + +import ( + "fmt" +) + +func main() { + randomNumbers := []int{13, 44, 56, 99, 9, 45, 67, 90, 78, 23} + // generate the common channel with inputs + inputChan := generatePipeline(randomNumbers) + + // Fan-out to 2 Go-routine + c1 := squareNumber(inputChan) + c2 := squareNumber(inputChan) + + // Fan-in the resulting squared numbers + c := fanIn(c1, c2) + sum := 0 + + // Do the summation + for i := 0; i < len(randomNumbers); i++ { + sum += <-c + } + fmt.Printf("Total Sum of Squares: %d", sum) +} + +func generatePipeline(numbers []int) <-chan int { + out := make(chan int) + go func() { + for _, n := range numbers { + out <- n + } + close(out) + }() + return out +} + +func squareNumber(in <-chan int) <-chan int { + out := make(chan int) + go func() { + for n := range in { + out <- n * n + } + close(out) + }() + return out +} + +func fanIn(input1, input2 <-chan int) <-chan int { + c := make(chan int) + go func() { + for { + select { + case s := <-input1: + c <- s + case s := <-input2: + c <- s + } + } + }() + return c +} diff --git a/concurrency/runner/main.go b/concurrency/runner/main.go new file mode 100644 index 0000000..3295e49 --- /dev/null +++ b/concurrency/runner/main.go @@ -0,0 +1,34 @@ +package main + +import ( + "errors" + "os" + "os/signal" + "time" +) + +type Runner struct { + interrupt chan os.Signal + complete chan error + timeout <-chan time.Time + tasks []func(int) +} + +var ErrTimeout = errors.New("Received Timeout") +var ErrInterrupt = errors.New("Received Interrupt") + +func New(d time.Duration) *Runner { + return &Runner{ + interrupt: make(chan os.Signal, 1), + complete: make(chan error), + timeout: time.After(d), + } +} + +func (r *Runner) Add(tasks ...func(int)) { + r.tasks = append(r.tasks, tasks...) +} + +func (r *Runner) Start() error { + signal.Notify(r.interrupt, os.Interrupt) +} diff --git a/idiom/passbyvalue/main.go b/idiom/passbyvalue/main.go new file mode 100644 index 0000000..2a675cd --- /dev/null +++ b/idiom/passbyvalue/main.go @@ -0,0 +1,45 @@ +package main + +import ( + "github.com/davecgh/go-spew/spew" +) + +type Person struct { + Name string + Age int +} + +func main() { + + s := "TTTT" + ps := &s + spew.Dump("ORIGINAL PS", ps) + spew.Dump("ADDRESS OF PS", &ps) + + pass(ps) + spew.Dump("The Value Of S", s) + p1 := &Person{"Jian", 23} + passStruct(p1) + spew.Dump("STRUCT AFTER PASSS STRUCT", p1) + +} + +func pass(ps *string) { + *ps = "ZZZZZZZZZZZZZZZZZ" + spew.Dump("PS IN PASS FUNCIONT", ps) + spew.Dump("ADDRESS OF PS IN PASS FUNCIONT", &ps) + ps = nil +} + +func passStruct(p *Person) { + p.Name = "Steve" + p = nil +} + +func passStruct2(p Person) { + p.Name = "Steve" +} + +func passVAL(v string) { + v = "" +}