原文链接: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. Codeforces Round #564 (Div. 2) C. Nauuo and Cards

    链接:https://codeforces.com/contest/1173/problem/C 题意: Nauuo is a girl who loves playing cards. One da ...

  2. Codeforces Round #433 (Div. 2, based on Olympiad of Metropolises) D

    Country of Metropolia is holding Olympiad of Metrpolises soon. It mean that all jury members of the ...

  3. 线程池(1)ThreadPoolExecutor梳理

    使用默认的 thread factory创建ThreadPoolExecutor实例 public ThreadPoolExecutor(int corePoolSize, int maximumPo ...

  4. WebStorm技巧-在安卓手机上运行Ionic程序

    打开菜单项 Run -> Run-   选择 Edit Configurations-   添加一个 PhoneGap/Cordova 配置项,命名如: Ionic Android, 并输入相关 ...

  5. P4878 道路修建-美国

    http://www.tyvj.cn/p/4878道路修建 我想我经大神点拨后终于明白了...回学校再写吧 时间限制:1s 内存限制:256MB [问题描述] A国是一个商业高度发达的国家.它包含了n ...

  6. Android 自定义Adapter中实现startActivityForResult的分析

    最近几天在做文件上传的时候,想在自定义Adapter中启动activity时也返回Intent数据,于是想到了用startActivityForResult,可是用mContext怎么也调不出这个方法 ...

  7. CSS 利用border三角形绘制方法

    CSS 三角形绘制方法,这里面的transparent比较重要,有和没有影响很大: 原理:这个div是由4个三角形组成,每个三角对应一个border,隐藏其它3个border,就可以得到一个三角形. ...

  8. C-C++字符输出时遇到字符'\n','\0'区别

    #include "iostream" #include "stdio.h" #include "stdio_ext.h" #include ...

  9. SQL Server数据库log shipping 灾备(Part2 )

    3.配置步骤: 主服务器(A机)设置 (1) 启用Log Shipping Configuration 右键单击需要配置日志传输的数据库->Tasks-> Ship Transaction ...

  10. Outlook 客户端无法通过 MAPI over HTTP协议 连接

    随着Exchange 版本更新升级,是否进行验证客户端建立MapiHttp连接所需的服务器设置已正确配置.即使服务器,负载均衡器和反向代理的所有设置都正确,您可能会遇到连接到Exchange Serv ...