原文链接: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. [TCP/IP]OSI七层模型和TCP/IP四层模型

    OSI參考模型 在過去的電腦網路上,由於資料通訊系統涉及複雜的軟硬體,可是又沒有統一的標準,導致通訊軟體不僅龐大複雜,而且不易測式.修改或分享.為此,ISO(國際標準組織)發展出一套OSI參考模型(O ...

  2. storm maven-shade-plugin

      storm-core pom <plugin> <groupId>org.apache.maven.plugins</groupId> <artifact ...

  3. C#远程连接sqlserver时,尝试读取或写入受保护的内存

    管理员身份运行 cmd ->  输入 netsh winsock reset

  4. Redis的数据类型(Strings、 hashes)

    字符串(Strings)类型及操作 字符串是Redis值的最基础的类型,一个key对应一个value,Redis字符串是二进制安全的,这意味着一个Redis字符串可以包含任何种类的数据,例如一个JPE ...

  5. 优化vue-cli构建的文件体积

    vue-router 懒加载优化 先安装 babel 动态引入插件 npm install --save-dev babel-plugin-syntax-dynamic-import 修改router ...

  6. Oracle中文乱码,字符集问题处理

    1. 右键计算机,选择属性,增加环境变量 NLS_LANG:SIMPLIFIED CHINESE_CHINA.ZHS16GBK 2.进入注册表,依次单击HKEY_LOCAL_MACHINE --> ...

  7. MySQL存储过程多条修改语句

    DROP procedure Sel_Function_ActivityPastDueDELIMITER $$DROP procedure IF EXISTS`shouyi`.`Sel_Functio ...

  8. 集合(Map、可变参数、Collections)

    集合 第1章 Map接口 1.1 Map接口概述 我们通过查看Map接口描述,发现Map接口下的集合与Collection接口下的集合,它们存储数据的形式不同,如下图. l Collection中的集 ...

  9. 【Unity3D】资源对象、预设、查找对象、组合模式等知识点

    1.解释对象与资源区别于联系,根据官方案例,分别总结资源和对象组织的规则/规律.    下载并查看了Adam和Survival Shooter tutorial两个官方资源案例,这些案例作为资源,可以 ...

  10. pm2-web监控

    pm2-web 是一款 pm2 服务状态监控程序,基于 web . 安装 npm install -g pm2-web 运行(默认占用8080端口) pm2-web 自定义配置文件 通过 --conf ...