美文网首页
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

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

  • nfs-ganesha - thread model - wor

    work pool 内部维护一个队列,生产者调用work_pool_submit将entry插入队列,有多个线程作...

  • Go每日精选(2019-06-17)

    1.golang fmt递归引起stack overflow异常 2.golang新版如何优化sync.pool锁...

  • golang sync .pool

    Go 是一个自动垃圾回收的编程语言,它的算法我们后续会讲到,主要就是采用三色并发标记算法标记对象并回收。我们可以不...

  • golang workpool , 工作池

    gowp golang worker pool ,线程池 , 工作池 并发限制goroutine池。 限制任务执行...

  • Golang sync.Pool 和 伪共享false shar

    参考go语言的官方包sync.Pool的实现原理和适用场景深入Golang之sync.Pool详解伪共享(fals...

  • go实现work_pool

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

  • golang sync.Pool

    临时对象池   当多个goroutine都需要创建同一个对象的时候,如果goroutine过多,可能导致对象的创建...

  • golang sync.Pool 分析

    在 echo 官网的手册上可以看到 echo 框架的路由性能主要依赖于 radix tree 和 sync.poo...

  • golang sync.pool对象复用 并发原理 缓存池

    golang sync.pool对象复用 并发原理 缓存池 在go http每一次go serve(l)都会构建R...

网友评论

      本文标题:golang: work pool

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