Golang

Golang 协程池小练习

Golang协程池

使用goroutine和channel实现一个计算int64随机数各位数和的程序

1 开启一个goroutine循环生成int64类型的随机数,发送到jobChan
2 开启24个goroutine从jobChan中取出随机数计算各位数的和,将结果发送到resultChan
3 主goroutine从resultChan中取出结果并打印输出到终端1

package main

import (
  "fmt"
  "math/rand"
  "sync"
  "time"
)



type job struct {
  value int64
}

type result struct {
  job *job
  sum int64
}

var jobChan = make(chan *job, 100)
var resultChan = make(chan *result, 100)

var wg sync.WaitGroup

func CreateRandom(r chan<- *job) {
  defer wg.Done()
  //循环生成int64的随机数,发送到jobChan
  for {
    x := rand.Int63()
    newJob := &job{value: x}
    r <- newJob
    time.Sleep(time.Second)
  }

}

func calc(r <-chan *job, resultChan chan<- *result) {
  defer wg.Done()
  //从jobChan中取出随机数计算各位数的和,将结果发送到resultChan
  for {
    everyJob := <-r
    sum := int64(0)
    n := everyJob.value
    for n > 0 {
      sum += n % 10
      n = n / 10
    }
    newResult := &result{
      job: everyJob,
      sum: sum,
    }
    resultChan <- newResult

  }

}

func main() {
  wg.Add(1)
  go CreateRandom(jobChan)
  //开启24个goroutine去执行
  wg.Add(24)
  for i := 0; i < 24; i++ {
    go calc(jobChan, resultChan)
  }
  //在主goroutine取到结果并打印
  for result := range resultChan {
    fmt.Printf("value : %d sum : %d\n", result.job.value, result.sum)

  }
  wg.Wait()

}

回复

This is just a placeholder img.