美文网首页
golang: work pool

golang: work pool

作者: 宋song一 | 来源:发表于2020-11-24 23:39 被阅读0次

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

    1. 开启一个goroutine循环生成int64类型的随机数,发送到jobChan
    2. 开启24个goroutine 从jobChan取出随机数并计算各位各位数的和,将结果发送到resultChan
    3. 主goroutine从resultChan取出结果并打印到终端输出
    package main
    
    import (
        "fmt"
        "math/rand"
        "sync"
        "time"
    )
    
    type Job struct {
        value int64
    }
    
    type Result struct {
        job *Job
        sum int64
    }
    
    var wg sync.WaitGroup
    var jobChan = make(chan *Job, 100)
    var resultChan = make(chan *Result, 100)
    
    func producer(job chan<- *Job) {
        defer wg.Done()
        for {
            newJob := &Job{
                value: rand.Int63(),
            }
            job <- newJob
            time.Sleep(time.Microsecond * 500)
        }
    }
    
    func consumer(z1 <-chan *Job, resultChan chan<- *Result) {
        defer wg.Done()
        for {
            job1 := <-z1
            result := int64(0)
            n := job1.value
            for n > 0 {
                result += n % 10
                n = n / 10
            }
            newResult := &Result{
                job: job1,
                sum: result,
            }
            resultChan <- newResult
        }
    }
    func main() {
        wg.Add(1)
        go producer(jobChan)
            wg.Add(24)
        for i := 0; i < 24; i++ {
            go consumer(jobChan, resultChan)
        }
        for result := range resultChan {
            fmt.Printf("value:%d sum:%d\n",result.job.value,result.sum)
        }
        wg.Wait()
    }
    
    

    相关文章

      网友评论

          本文标题:golang: work pool

          本文链接:https://www.haomeiwen.com/subject/pkxgiktx.html