1.简单的生成器
- package main
-
- import (
- "fmt"
- "math/rand"
- )
-
- func GenerateIntA()chan int {
- ch := make(chan int ,10)
- go func(){
- for {
- ch<-rand.Int()
- }
- }()
- return ch
- }
-
- func main(){
- ch := GenerateIntA()
- fmt.Println(<-ch)
- fmt.Println(<-ch)
- }
2.叠加增强型资源生成器
可以使用多路复用技术进行堆积叠加,增加服务能力
可以使用缓冲chan增加服务能力
- package main
-
- import (
- "fmt"
- "math/rand"
- )
-
- func GenerateIntA() chan int {
- ch := make(chan int, 10)
- go func() {
- for {
- ch <- rand.Int()
- }
- }()
- return ch
- }
-
- func GenerateIntB() chan int {
- ch := make(chan int, 10)
- go func() {
- for {
- ch <- rand.Int()
- }
- }()
- return ch
- }
-
- func GenerateInt() chan int {
- ch := make(chan int, 20)
- go func() {
- for {
- select {
- case ch <- <-GenerateIntA():
- case ch <- <-GenerateIntB():
- }
- }
- }()
- return ch
- }
-
- func main() {
- ch := GenerateInt()
-
- for i := 0; i < 100; i++ {
- fmt.Println(<-ch)
- }
- }
3.有时我们希望生成器能够自动的退出,这时可以使用golang channel的
Close channel to broadcast 机制实现:
- package main
-
- import (
- "fmt"
- "math/rand"
- )
-
- func GenerateIntA(done chan struct{})chan int {
- ch := make(chan int )
- go func(){
- Lable:
- for {
- select {
- case ch<-rand.Int():
- case <-done:
- break Lable
- }
- }
- close(ch)
- }()
- return ch
- }
-
- func main(){
- done :=make(chan struct{})
- ch := GenerateIntA(done)
-
- fmt.Println(<-ch)
- fmt.Println(<-ch)
- close(done)
- fmt.Println(<-ch)
- fmt.Println(<-ch)
- fmt.Println(<-ch)
- fmt.Println(<-ch)
- }
4.可以更牛逼点,既要并发、缓冲,又有通知的生成器:
- package main
-
- import (
- "fmt"
- "math/rand"
- )
-
- func GenerateIntA(done chan struct{}) chan int {
- ch := make(chan int, 5)
-
- go func() {
- Lable:
- for {
- select {
- case ch <- rand.Int():
- case <-done:
- break Lable
- }
- }
- close(ch)
- }()
- return ch
- }
-
- func GenerateIntB(done chan struct{}) chan int {
- ch := make(chan int, 10)
-
- go func() {
- Lable:
- for {
- select {
- case ch <- rand.Int():
- case <-done:
- break Lable
- }
- }
- close(ch)
- }()
- return ch
- }
-
- func GenerateInt(done chan struct{}) chan int {
- ch := make(chan int)
- send := make(chan struct{})
- go func() {
- Lable:
- for {
- select {
- case ch <- <-GenerateIntA(send):
- case ch <- <-GenerateIntB(send):
- case <-done:
- send <- struct{}{}
- send <- struct{}{}
- break Lable
- }
- }
- close(ch)
- }()
- return ch
- }
-
- func main() {
- done := make(chan struct{})
- ch := GenerateInt(done)
-
- for i := 0; i < 10; i++ {
- fmt.Println(<-ch)
- }
- done <- struct{}{}
- for i := 0; i < 10; i++ {
- v := <-ch
- if v == 0 {
- return
- }
- fmt.Println(<-ch)
- }
- }
|
请发表评论