原文链接:https://golangbot.com/buffered-channels-worker-pools/

buffered channels

  • 带有缓冲区的channel 只有在缓冲区满之后 channel才会阻塞

WaitGroup

  • 如果有多个 goroutine在后台执行 那么需要在主线程中 多次等待 可以有一个简单的方法 就是 通过WaitGroup 可以控制 Goroutines 直到它们都执行完成

例子

import (
"fmt"
"sync"
"time"
) func process(i int, wg *sync.WaitGroup) {
fmt.Println("started Goroutine ", i)
time.Sleep(2 * time.Second)
fmt.Printf("Goroutine %d ended\n", i)
wg.Done()
} func main() {
no := 3
var wg sync.WaitGroup
for i := 0; i < no; i++ {
wg.Add(1)
go process(i, &wg)
}
wg.Wait()![](https://images2018.cnblogs.com/blog/736597/201803/736597-20180312115109926-1714494090.png) fmt.Println("All go routines finished executing")
}

Worker Pool Implementation

先贴一下个人理解的 程序执行的流程图

import (
"fmt"
"math/rand"
"sync"
"time"
) type Job struct {
id int
randomno int
}
type Result struct {
job Job
sumofdigits int
} var jobs = make(chan Job, 10)
var results = make(chan Result, 10) func digits(number int) int {
sum := 0
no := number
for no != 0 {
digit := no % 10
sum += digit
no /= 10
}
time.Sleep(5 * time.Second)
return sum
}
func worker(wg *sync.WaitGroup) {
for job := range jobs {
output := Result{job, digits(job.randomno)}
results <- output
}
wg.Done()
}
func createWorkerPool(noOfWorkers int) {
var wg sync.WaitGroup
for i := 0; i < noOfWorkers; i++ {
wg.Add(1)
go worker(&wg)
}
wg.Wait()
close(results)
}
func allocate(noOfJobs int) {
for i := 0; i < noOfJobs; i++ {
randomno := rand.Intn(999)
job := Job{i, randomno}
jobs <- job
}
close(jobs)
}
func result(done chan bool) {
for result := range results {
fmt.Printf("Job id %d, input random no %d , sum of digits %d\n", result.job.id, result.job.randomno, result.sumofdigits)
}
done <- true
} func main() {
startTime := time.Now() noOfJobs := 100
go allocate(noOfJobs) done := make(chan bool)
go result(done)
noOfWorkers := 10
createWorkerPool(noOfWorkers)
<-done endTime := time.Now() diff := endTime.Sub(startTime)
fmt.Println("total time taken ", diff.Seconds(), "seconds")
}

Buffered Channels and Worker Pools的更多相关文章

  1. 【Go入门教程7】并发(goroutine,channels,Buffered Channels,Range和Close,Select,超时,runtime goroutine)

    有人把Go比作21世纪的C语言,第一是因为Go语言设计简单,第二,21世纪最重要的就是并行程序设计,而Go从语言层面就支持了并行. goroutine goroutine是Go并行设计的核心.goro ...

  2. 【Go入门教程9】并发(goroutine,channels,Buffered Channels,Range和Close,Select,超时,runtime goroutine)

    有人把Go比作21世纪的C语言,第一是因为Go语言设计简单,第二,21世纪最重要的就是并行程序设计,而Go从语言层面就支持了并行. goroutine goroutine是Go并行设计的核心.goro ...

  3. A Tour of Go Buffered Channels

    Channels can be buffered. Provide the buffer length as the second argument to make to initialize a b ...

  4. GO系列教程

    1.介绍与安装 2.Hello World 3.变量 4. 类型 5.常量 6.函数(Function) 7.包 8.if-else 语句 9.循环 10.switch语句 11.数组和切片 12.可 ...

  5. goroutine与channels

    goroutine(协程) 大家都知道java中的线程Thread,golang没有提供Thread的功能,但是提供了更轻量级的goroutine(协程),协程比线程更轻,创办一个协程很简单,只需要g ...

  6. 【转】 Anatomy of Channels in Go - Concurrency in Go

    原文:https://medium.com/rungo/anatomy-of-channels-in-go-concurrency-in-go-1ec336086adb --------------- ...

  7. golang中channels的本质详解,经典!

    原文:https://www.goinggo.net/2014/02/the-nature-of-channels-in-go.html The Nature Of Channels In Go 这篇 ...

  8. Why should I avoid blocking the Event Loop and the Worker Pool?

    Don't Block the Event Loop (or the Worker Pool) | Node.js https://nodejs.org/en/docs/guides/dont-blo ...

  9. Go by Example

    Go by Example Go is an open source programming language designed for building simple, fast, and reli ...

随机推荐

  1. HDU-2119-Matrix(最大匹配)

    链接:https://vjudge.net/problem/HDU-2119#author=Smilencer 题意: 众所周知,tyz是一个写bug小能手,以至于如果没有队友的帮助,就ac不了程序. ...

  2. 实例/静态工厂方法得到bean

    <bean id="a" class="com.yundaex.wms.config.TestBeanChild" /> <bean id=& ...

  3. jQuery解决ajax请求的跨域问题

    这两天工作中频繁的遇到JS的跨域问题,都通过绕开ajax请求的方式.特地百度了一下,把跨域问题解决了.在这分析一下 首先贴上js的页面代码: <html> <head> < ...

  4. 1550: Simple String 最大流解法

    http://acm.csu.edu.cn/csuoj/problemset/problem?pid=1550 很久以前做的一题,当时队友用最大流做,现在我也是 这个转化为二分图多重匹配,就是一样的意 ...

  5. 作用域提升(Scope Hositing )是 Webpack 3 的标志性特征

    http://blog.csdn.net/playboyanta123/article/details/73533079

  6. 《javascript设计模式》笔记之第九章:组合模式

    之前一直都是按照书的结构顺序做总结,觉得好像不是很好,现在试着完全按照自己的理解做总结.例子还是书上的例子. 一:组合模式的作用: 在web开发中,主要用于创建嵌套的html结点,使得我们方便的把各种 ...

  7. mysql explain 的extra中using index ,using where,using index condition,using index & using where理解

    using index :查找使用了索引,查询结果覆盖了索引 using where:查找使用了索引,不需要回表去查询所需的数据,查询结果是索引的一部分 using index condition:查 ...

  8. Php—AJAX跨域问题

    <?php /** * ajax proxy * ajax跨域解决办法 * @author  suconghou <suconghou@126.com> * @version v1. ...

  9. JAVA分包下项目部分代码存储

    一.注册时姓名去重和符合汉字格式: // 新用户申请加入 public void NewHuman() { System.out.println("========新会员申请加入页面==== ...

  10. java实现按对象某个字段排序,排序字段和规则自定义

    @SuppressWarnings({ "unchecked", "rawtypes" }) private <T> void sort(List& ...