在随机数生成器,多个goroutine增强型示例中,使用for循环,利用select随机调用 GenerateIntA()、GenerateIntB()两个方法来取随机数时,每次调用都会生成一个新的goroutine,每个goroutine只被使用一次。这与使用两个goroutine提供随机数,一个goroutine随机选择的初衷不符。另外,也不需要定义两个完全一模一样的方法(GenerateA、GenerateB),只需要定义一个,调用两次,就能生成两个goroutine,同时返回了两个channel.可以调整为下面这样:package main
import ( “fmt” “math/rand” “runtime” “time”)
func GenerateIntA() chan int { ch := make(chan int, 10) go func() { for { ch <- rand.Int() } }() return ch}
func GenerateInt() chan int { ch := make(chan int, 20) ch1 := GenerateIntA() ch2 := GenerateIntA() go func() { for { select { case ch <- <-ch1: case ch <- <-ch2: } } }() return ch}
func main() { ch := GenerateInt() time.Sleep(3 * time.Second) fmt.Printf(“NumGoroutine: %d, GOMAXPROCS:%d\n”, runtime.NumGoroutine(), runtime.GOMAXPROCS(0)) for i := 0; i < 15; i++ { fmt.Printf(“%d\t”, i) fmt.Println(<-ch) }}
func DistributeTask(taskchan <- chan task, …)应该为func DistributeTask(taskchan chan task, …)
图6-1中的 按照能否为类型添加方法划分 中,私以为简单类型(如 int)是不能添加自定义方法的。
在随机数生成器,多个goroutine增强型示例中,使用for循环,利用select随机调用 GenerateIntA()、GenerateIntB()两个方法来取随机数时,每次调用都会生成一个新的goroutine,每个goroutine只被使用一次。
这与使用两个goroutine提供随机数,一个goroutine随机选择的初衷不符。
另外,也不需要定义两个完全一模一样的方法(GenerateA、GenerateB),只需要定义一个,调用两次,就能生成两个goroutine,同时返回了两个channel.
可以调整为下面这样:
package main
import (
“fmt”
“math/rand”
“runtime”
“time”
)
func GenerateIntA() chan int {
ch := make(chan int, 10)
go func() {
for {
ch <- rand.Int()
}
}()
return ch
}
func GenerateInt() chan int {
ch := make(chan int, 20)
ch1 := GenerateIntA()
ch2 := GenerateIntA()
go func() {
for {
select {
case ch <- <-ch1:
case ch <- <-ch2:
}
}
}()
return ch
}
func main() {
ch := GenerateInt()
time.Sleep(3 * time.Second)
fmt.Printf(“NumGoroutine: %d, GOMAXPROCS:%d\n”, runtime.NumGoroutine(), runtime.GOMAXPROCS(0))
for i := 0; i < 15; i++ {
fmt.Printf(“%d\t”, i)
fmt.Println(<-ch)
}
}
func DistributeTask(taskchan <- chan task, …)
应该为
func DistributeTask(taskchan chan task, …)
图6-1中的 按照能否为类型添加方法划分 中,私以为简单类型(如 int)是不能添加自定义方法的。