concurrency/generator: merge the source and the pattern files

This commit is contained in:
Tamer Tas
2016-09-15 11:39:40 +03:00
parent 89df9f0955
commit d717978979
2 changed files with 34 additions and 27 deletions

View File

@@ -1,7 +1,38 @@
# Generator Pattern
[Generators](https://en.wikipedia.org/wiki/Generator_(computer_programming)) yields a sequence of values one at a time
[Generators](https://en.wikipedia.org/wiki/Generator_(computer_programming)) yields a sequence of values one at a time.
# Implementation and Example
## Implementation
You can find the implementation and usage in [generator.go](generator.go)
```go
func Count(start int, end int) chan int {
ch := make(chan int)
go func(ch chan int) {
for i := start; i < end ; i++ {
// Blocks on the operation
ch <- result
}
close(ch)
}(ch)
return ch
}
```
## Usage
```go
fmt.Println("No bottles of beer on the wall")
for i := range Count(1, 99) {
fmt.Println("Pass it around, put one up,", i, "bottles of beer on the wall")
// Pass it around, put one up, 1 bottles of beer on the wall
// Pass it around, put one up, 2 bottles of beer on the wall
// ...
// Pass it around, put one up, 99 bottles of beer on the wall
}
fmt.Println(100, "bottles of beer on the wall")
```