Skip to content

Commit d05638a

Browse files
legendtkltmrts
authored andcommitted
concurrency/generator: implement generator pattern
1 parent 90f5b5b commit d05638a

File tree

3 files changed

+50
-1
lines changed

3 files changed

+50
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ A curated collection of idiomatic design & application patterns for Go language.
6767
| [Bounded Parallelism](/concurrency/bounded_parallelism.md) | Completes large number of independent tasks with resource limits ||
6868
| [Broadcast](/concurrency/broadcast.md) | Transfers a message to all recipients simultaneously ||
6969
| [Coroutines](/concurrency/coroutine.md) | Subroutines that allow suspending and resuming execution at certain locations ||
70-
| [Generators](/concurrency/generator.md) | Yields a sequence of values one at a time | |
70+
| [Generators](/concurrency/generator.md) | Yields a sequence of values one at a time | |
7171
| [Reactor](/concurrency/reactor.md) | Demultiplexes service requests delivered concurrently to a service handler and dispatches them syncronously to the associated request handlers ||
7272
| [Parallelism](/concurrency/parallelism.md) | Completes large number of independent tasks ||
7373
| [Producer Consumer](/concurrency/producer_consumer.md) | Separates tasks from task executions ||

concurrency/generator.md

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
# Generator Pattern
2+
3+
[Generator](https://en.wikipedia.org/wiki/Generator_(computer_programming)) is a special routine that can be used to control the iteration behavior of a loop.
4+
5+
# Implementation and Example
6+
With Go language, we can implement generator in two ways: channel and closure. Fibonacci number generation example can be found in [generators.go](generators.go).

concurrency/generators.go

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
)
6+
7+
//FibonacciClosure implements fibonacci number generation using closure
8+
func FibonacciClosure() func() int {
9+
a, b := 0, 1
10+
return func() int {
11+
a, b = b, a+b
12+
return a
13+
}
14+
}
15+
16+
//FibonacciChan implements fibonacci number generation using channel
17+
func FibonacciChan(n int) chan int {
18+
c := make(chan int)
19+
20+
go func() {
21+
a, b := 0, 1
22+
for i := 0; i < n; i++ {
23+
c <- b
24+
a, b = b, a+b
25+
}
26+
close(c)
27+
}()
28+
29+
return c
30+
}
31+
32+
func main() {
33+
//closure
34+
nextFib := FibonacciClosure()
35+
for i := 0; i < 20; i++ {
36+
fmt.Println(nextFib())
37+
}
38+
39+
//channel
40+
for i := range FibonacciChan(20) {
41+
fmt.Println(i)
42+
}
43+
}

0 commit comments

Comments
 (0)