Created
September 25, 2014 01:11
-
-
Save diegomrodz/b2dad686c0e9cc470578 to your computer and use it in GitHub Desktop.
Padrões de Concorrencia em Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"sync" | |
) | |
func gen(done <-chan struct{}, nums ...int) <-chan int { | |
out := make(chan int, len(nums)) | |
go func () { | |
defer close(out) | |
for _, n := range nums { | |
select { | |
case out <- n: | |
case <-done: | |
return | |
} | |
} | |
}() | |
return out | |
} | |
func sq(done <-chan struct{}, in <-chan int) <-chan int { | |
out := make(chan int) | |
go func() { | |
defer close(out) | |
for n := range in { | |
select { | |
case out <- n * n: | |
case <-done: | |
return | |
} | |
} | |
}() | |
return out | |
} | |
func merge(done <-chan struct{}, cs ...<-chan int) <-chan int { | |
var wg sync.WaitGroup | |
out := make(chan int, 1) | |
output := func(c <-chan int) { | |
defer wg.Done() | |
for n := range c { | |
select { | |
case out <- n: | |
case <-done: | |
return | |
} | |
} | |
} | |
wg.Add(len(cs)) | |
for _, c := range cs { | |
go output(c) | |
} | |
go func() { | |
wg.Wait() | |
close(out) | |
}() | |
return out | |
} | |
func main () { | |
done := make(chan struct{}) | |
defer close(done) | |
in := gen(done, 2, 3) | |
c1 := sq(done, in) | |
c2 := sq(done, in) | |
out := merge(done, c1, c2) | |
fmt.Println(<-out) | |
fmt.Println(<-out) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment