66 lines
1.3 KiB
Go
66 lines
1.3 KiB
Go
|
package main
|
|||
|
|
|||
|
import (
|
|||
|
"fmt"
|
|||
|
"math/rand"
|
|||
|
"sync"
|
|||
|
"time"
|
|||
|
)
|
|||
|
|
|||
|
//使用 goroutine 和 channel 实现一个计算int64随机数各位数和的程序,例如生成随机数61345,计算其每个位数上的数字之和为19。
|
|||
|
//开启一个 goroutine 循环生成int64类型的随机数,发送到jobChan
|
|||
|
//开启24个 goroutine 从jobChan中取出随机数计算各位数的和,将结果发送到resultChan
|
|||
|
//主 goroutine 从resultChan取出结果并打印到终端输出
|
|||
|
|
|||
|
var w sync.WaitGroup
|
|||
|
|
|||
|
type job struct {
|
|||
|
value int64
|
|||
|
}
|
|||
|
type Result struct {
|
|||
|
job *job
|
|||
|
sum int64
|
|||
|
}
|
|||
|
|
|||
|
var jobChan = make(chan *job, 100)
|
|||
|
var resultChan = make(chan *Result, 100)
|
|||
|
|
|||
|
func producer(prod chan<- *job) <-chan *job {
|
|||
|
defer w.Done()
|
|||
|
for {
|
|||
|
x := rand.Int63()
|
|||
|
newJob := &job{value: x}
|
|||
|
jobChan <- newJob
|
|||
|
time.Sleep(time.Millisecond * 500)
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
func consumer(con chan<- *Result, prod <-chan *job) {
|
|||
|
defer w.Done()
|
|||
|
for {
|
|||
|
v := <-prod
|
|||
|
sum := int64(0)
|
|||
|
n := v.value
|
|||
|
for n > 0 {
|
|||
|
sum += n % 10
|
|||
|
n = n / 10
|
|||
|
}
|
|||
|
newResult := &Result{job: v, sum: sum}
|
|||
|
con <- newResult
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
func main() {
|
|||
|
w.Add(1)
|
|||
|
go producer(jobChan)
|
|||
|
w.Add(24)
|
|||
|
for i := 0; i < 24; i++ {
|
|||
|
go consumer(resultChan, jobChan)
|
|||
|
}
|
|||
|
for i := range resultChan {
|
|||
|
fmt.Printf("随机数为:%d,加和为:%d\n", i.job.value, i.sum)
|
|||
|
}
|
|||
|
w.Wait()
|
|||
|
|
|||
|
}
|