原文链接: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. JavaWeb项目开发中eclipse缓存问题

    学习Java快2年了 有时候改完代码启动tomcat测试时,新代码不生效,这可能就是缓存问题. 所以平时就用以下几个方法解决,如果还是解决不了,就找老师吧! 1.清理项目 2.移除项目,清理tomca ...

  2. .net framework MVC 下 Hangfire使用,时区,权限

    安装 NuGet 上有几个可用的Hangfire 的软件包.如果在ASP.NET应用程序中安装HangFire,并使用Sql Server作为存储器,那么请在Package Manager Conso ...

  3. 绕过UAC以管理员身份启动程序

    写这篇文章主要是看到了:http://www.7tutorials.com/use-task-scheduler-launch-programs-without-uac-prompts文章中所用到的方 ...

  4. 1169 传纸条 2008年NOIP全国联赛提高组 个人博客:attack.cf

    1169 传纸条 2008年NOIP全国联赛提高组 时间限制: 1 s 空间限制: 128000 KB 题目等级 : 钻石 Diamond         题目描述 Description 小渊和小轩 ...

  5. 字典(dict),增删改查,嵌套

    一丶字典 dict 用{}来表示  键值对数据  {key:value}  唯一性 键 都必须是可哈希的 不可变的数据类型就可以当做字典中的键 值 没有任何限制 二丶字典的增删改查 1.增 dic[k ...

  6. javaweb-servlet生成简单的验证码

    package com.serv; import java.awt.Color; import java.awt.Graphics; import java.awt.image.BufferedIma ...

  7. $.ajax同步/异步(async:false/true)

    虽然说ajax用来执行异步请求的比较多,但有时还是存在需要同步执行的情况的. 比如:我需要通过ajax取执行请求以返回一个值,这个值在ajax后面是需要使用到的,这时就不能用异步请求了.这时候就需要使 ...

  8. <Android Framework 之路>多线程

    多线程编程 JAVA多线程方式 1. 继承Thread线程,实现run方法 2. 实现Runnable接口 JAVA单继承性,当我们想将一个已经继承了其他类的子类放到Thread中时,单继承的局限就体 ...

  9. bootstrap中container和container-fluid的区别与用法

    对bootstrap框架有一定了解的朋友都知道,一般页面布局中的开头会使用到container或container-fluid类,那么它们有什么区别呢?不急!下面为您讲解. 我们先来看看官方对这两个类 ...

  10. 【extjs6学习笔记】0.1 准备:基础概念(02)

    Ext 类 Ext 是一个全局单例的对象,在 Sencha library 中它封装了所有的类和许多实用的方法.许多常用的函数都定义在 Ext 对象里.它还提供了像其他类中一些频繁使用的方法的快速调用 ...