SlideShare a Scribd company logo
Go Concurrency
March 27, 2013

John Graham-Cumming

www.cloudflare.com!
Fundamentals
•  goroutines
•  Very lightweight processes
•  All scheduling handled internally by the Go runtime
•  Unless you are CPU bound you do not have to think about
scheduling

•  Channel-based communication
•  The right way for goroutines to talk to each other

•  Synchronization Primitives
•  For when a channel is too heavyweight
•  Not covered in this talk

www.cloudflare.com!
goroutines
•  “Lightweight”
•  Starting 10,000 goroutines on my MacBook Pro took 22ms
•  Allocated memory increased by 3,014,000 bytes (301 bytes per
goroutine)
•  https://gist.github.com/jgrahamc/5253020
•  Not unusual at CloudFlare to have a single Go program

running 10,000s of goroutines with 1,000,000s of
goroutines created during life program.

•  So, go yourFunc() as much as you like.

www.cloudflare.com!
Channels
•  Quick syntax review

c := make(chan bool)– Makes an unbuffered
channel of bools
c <- x – Sends a value on the channel
<- c – Waits to receive a value on the channel
x = <- c – Waits to receive a value and stores it in x
x, ok = <- c – Waits to receive a value; ok will be
false if channel is closed and empty.

www.cloudflare.com!
Unbuffered channels are best
•  They provide both communication and synchronization
func from(connection chan int) {!
connection <- rand.Intn(100)!
}!
!
func to(connection chan int) {!
i := <- connection!
fmt.Printf("Someone sent me %dn", i)!
}!
!
func main() {!
cpus := runtime.NumCPU()!
runtime.GOMAXPROCS(cpus)!
!
connection := make(chan int)!
go from(connection)!
go to(connection)!
}!
www.cloudflare.com!
Using channels for signaling
(1)
•  Sometimes just closing a channel is enough
c := make(chan bool)!
!
go func() {!
!// ... do some stuff!
!close(c)!
}()!
!
// ... do some other stuff!
<- c!

www.cloudflare.com!
Using channels for signaling (2) 
•  Close a channel to coordinate multiple goroutines
func worker(start chan bool) {!
<- start!
// ... do stuff!
}!
!
func main() {!
start := make(chan bool)!
!
for i := 0; i < 100; i++ {!
go worker(start)!
}!
!
close(start)!
!
// ... all workers running now!
}!
www.cloudflare.com!
Select
•  Select statement enables sending/receiving on multiple

channels at once
select {!
case x := <- somechan:!
// ... do stuff with x!
!
case y, ok := <- someOtherchan:!
// ... do stuff with y!
// check ok to see if someOtherChan!
// is closed!
!
case outputChan <- z:!
// ... ok z was sent!
!
default:!
// ... no one wants to communicate!
}!
www.cloudflare.com!
Common idiom: for/select!
for {!
select {!
case x := <- somechan:!
// ... do stuff with x!
!
case y, ok := <- someOtherchan:!
// ... do stuff with y!
// check ok to see if someOtherChan!
// is closed!
!
case outputChan <- z:!
// ... ok z was sent!
!
default:!
// ... no one wants to communicate!
}!
}!

www.cloudflare.com!
Using channels for signaling (4)
•  Close a channel to terminate multiple goroutines
func worker(die chan bool) {!
for {!
select {!
// ... do stuff cases!
case <- die: !
return!
}!
}!
}!
!
func main() {!
die := make(chan bool)!
for i := 0; i < 100; i++ {!
go worker(die)!
}!
close(die)!
}!
www.cloudflare.com!
Using channels for signaling (5)
•  Terminate a goroutine and verify termination
func worker(die chan bool) {!
for {!
select {!
// ... do stuff cases!
case <- die:!
// ... do termination tasks !
die <- true!
return!
}!
}!
}!
func main() {!
die := make(chan bool)!
go worker(die)!
die <- true!
<- die!
}!
www.cloudflare.com!
Example: unique ID service
•  Just receive from id to get a unique ID
•  Safe to share id channel across routines
id := make(chan string)!
!
go func() {!
var counter int64 = 0!
for {!
id <- fmt.Sprintf("%x", counter)!
counter += 1!
}!
}()!
!
x := <- id // x will be 1!
x = <- id // x will be 2!

www.cloudflare.com!
Example: memory recycler
func recycler(give, get chan []byte) {!
q := new(list.List)!
!
for {!
if q.Len() == 0 {!
q.PushFront(make([]byte, 100))!
}!
!
e := q.Front()!
!
select {!
case s := <-give:!
q.PushFront(s[:0])!
!
case get <- e.Value.([]byte):!
q.Remove(e)!
}!
}!
}!
www.cloudflare.com!
Timeout
func worker(start chan bool) {!
for {!
!timeout := time.After(30 * time.Second)!
!select {!
// ... do some stuff!
!
case <- timeout:!
return!
}!
func worker(start chan bool) {!
}!
timeout := time.After(30 * time.Second)!
}!
for {!
!select {!
// ... do some stuff!
!
case <- timeout:!
return!
}!
}!
}!
www.cloudflare.com!
Heartbeat
func worker(start chan bool) {!
heartbeat := time.Tick(30 * time.Second)!
for {!
!select {!
// ... do some stuff!
!
case <- heartbeat:!
// ... do heartbeat stuff!
}!
}!
}!

www.cloudflare.com!
Example: network multiplexor
•  Multiple goroutines can send on the same channel
func worker(messages chan string) {!
for {!
var msg string // ... generate a message!
messages <- msg!
}!
}!
func main() {!
messages := make(chan string)!
conn, _ := net.Dial("tcp", "example.com")!
!
for i := 0; i < 100; i++ {!
go worker(messages)!
}!
for {!
msg := <- messages!
conn.Write([]byte(msg))!
}!
}!

www.cloudflare.com!
Example: first of N
•  Dispatch requests and get back the first one to complete
type response struct {!
resp *http.Response!
url string!
}!
!
func get(url string, r chan response ) {!
if resp, err := http.Get(url); err == nil {!
r <- response{resp, url}!
}!
}!
!
func main() {!
first := make(chan response)!
for _, url := range []string{"http://code.jquery.com/jquery-1.9.1.min.js",!
"http://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js",!
"http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js",!
"http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js"} {!
go get(url, first)!
}!
!
r := <- first!
// ... do something!
}!
www.cloudflare.com!
range!
•  Can be used to consume all values from a channel
func generator(strings chan string) {!
strings <- "Five hour's New York jet lag"!
strings <- "and Cayce Pollard wakes in Camden Town"!
strings <- "to the dire and ever-decreasing circles"!
strings <- "of disrupted circadian rhythm."!
close(strings)!
}!
!
func main() {!
strings := make(chan string)!
go generator(strings)!
!
for s := range strings {!
fmt.Printf("%s ", s)!
}!
fmt.Printf("n");!
}!
www.cloudflare.com!
Passing a ‘response’ channel
type work struct {!
url string!
resp chan *http.Response!
}!
!
func getter(w chan work) {!
for {!
do := <- w!
resp, _ := http.Get(do.url)!
do.resp <- resp!
}!
}!
!
func main() {!
w := make(chan work)!
!
go getter(w)!
!
resp := make(chan *http.Response)!
w <- work{"http://cdnjs.cloudflare.com/jquery/1.9.1/jquery.min.js",!
resp}!
!
r := <- resp!
}!
www.cloudflare.com!
Buffered channels
•  Can be useful to create queues
•  But make reasoning about concurrency more difficult

c := make(chan bool, 100) !

www.cloudflare.com!
Example: an HTTP load balancer
•  Limited number of HTTP clients can make requests for

URLs
•  Unlimited number of goroutines need to request URLs
and get responses

•  Solution: an HTTP request load balancer

www.cloudflare.com!
A URL getter
type job struct {!
url string!
resp chan *http.Response!
}!
!
type worker struct {!
jobs chan *job!
count int!
}!
!
func (w *worker) getter(done chan *worker) {!
for {!
j := <- w.jobs!
resp, _ := http.Get(j.url)!
j.resp <- resp!
done <- w!
}!
}!
www.cloudflare.com!
A way to get URLs
func get(jobs chan *job, url string, answer chan string) {!
resp := make(chan *http.Response)!
jobs <- &job{url, resp}!
r := <- resp!
answer <- r.Request.URL.String()!
}!
!
func main() {!
jobs := balancer(10, 10)!
answer := make(chan string)!
for {!
var url string!
if _, err := fmt.Scanln(&url); err != nil {!
break!
}!
go get(jobs, url, answer)!
}!
for u := range answer {!
fmt.Printf("%sn", u)!
}!
}!
www.cloudflare.com!
A load balancer
func balancer(count int, depth int) chan *job {!
jobs := make(chan *job)!
done := make(chan *worker)!
workers := make([]*worker, count)!
!
for i := 0; i < count; i++ {!
workers[i] = &worker{make(chan *job,

depth), 0}!
go workers[i].getter(done)!
}!
!
!
select {!
go func() {!
case j := <- jobsource:!
for {!
free.jobs <- j!
var free *worker!
free.count++!
min := depth!
!
for _, w := range workers {!
case w := <- done:!
if w.count < min {!
w.count—!
free = w!
}!
min = w.count!
}!
}!
}()!
}!
!
!
return jobs!
var jobsource chan *job!
}!
if free != nil {!
jobsource = jobs!
}!
www.cloudflare.com!
Top 500 web sites loaded

www.cloudflare.com!
THANKS
The Go Way: “small sequential pieces joined
by channels”

www.cloudflare.com!

More Related Content

What's hot

Playing With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.jsPlaying With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.js
Mike Hagedorn
 
HAB Software Woes
HAB Software WoesHAB Software Woes
HAB Software Woes
jgrahamc
 
Introduction to kotlin coroutines
Introduction to kotlin coroutinesIntroduction to kotlin coroutines
Introduction to kotlin coroutines
NAVER Engineering
 
Beyond Page Level Metrics
Beyond Page Level MetricsBeyond Page Level Metrics
Beyond Page Level Metrics
Philip Tellis
 
marko_go_in_badoo
marko_go_in_badoomarko_go_in_badoo
marko_go_in_badooMarko Kevac
 
Javascript Everywhere
Javascript EverywhereJavascript Everywhere
Javascript Everywhere
Pascal Rettig
 
All you need to know about the JavaScript event loop
All you need to know about the JavaScript event loopAll you need to know about the JavaScript event loop
All you need to know about the JavaScript event loop
Saša Tatar
 
Coroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in PractiseCoroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in Practise
Christian Melchior
 
Coroutines talk ppt
Coroutines talk pptCoroutines talk ppt
Coroutines talk ppt
Shahroz Khan
 
Async java8
Async java8Async java8
Async java8
Murali Pachiyappan
 
Real Time Event Dispatcher
Real Time Event DispatcherReal Time Event Dispatcher
Real Time Event Dispatcher
Peter Dietrich
 
Event loop
Event loopEvent loop
Event loop
codepitbull
 
연구자 및 교육자를 위한 계산 및 분석 플랫폼 설계 - PyCon KR 2015
연구자 및 교육자를 위한 계산 및 분석 플랫폼 설계 - PyCon KR 2015연구자 및 교육자를 위한 계산 및 분석 플랫폼 설계 - PyCon KR 2015
연구자 및 교육자를 위한 계산 및 분석 플랫폼 설계 - PyCon KR 2015
Jeongkyu Shin
 
A Gentle Introduction to Event Loops
A Gentle Introduction to Event LoopsA Gentle Introduction to Event Loops
A Gentle Introduction to Event Loops
deepfountainconsulting
 
JavaScript Engines and Event Loop
JavaScript Engines and Event Loop JavaScript Engines and Event Loop
JavaScript Engines and Event Loop
Tapan B.K.
 
Domains!
Domains!Domains!
DevOps(3) : Ansible - (MOSG)
DevOps(3) : Ansible - (MOSG)DevOps(3) : Ansible - (MOSG)
DevOps(3) : Ansible - (MOSG)
Soshi Nemoto
 
Boom! Promises/A+ Was Born
Boom! Promises/A+ Was BornBoom! Promises/A+ Was Born
Boom! Promises/A+ Was Born
Domenic Denicola
 
DJUGL - Django and AWS Lambda
DJUGL - Django and AWS LambdaDJUGL - Django and AWS Lambda
DJUGL - Django and AWS Lambda
Malcolm Box
 
node.js and native code extensions by example
node.js and native code extensions by examplenode.js and native code extensions by example
node.js and native code extensions by example
Philipp Fehre
 

What's hot (20)

Playing With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.jsPlaying With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.js
 
HAB Software Woes
HAB Software WoesHAB Software Woes
HAB Software Woes
 
Introduction to kotlin coroutines
Introduction to kotlin coroutinesIntroduction to kotlin coroutines
Introduction to kotlin coroutines
 
Beyond Page Level Metrics
Beyond Page Level MetricsBeyond Page Level Metrics
Beyond Page Level Metrics
 
marko_go_in_badoo
marko_go_in_badoomarko_go_in_badoo
marko_go_in_badoo
 
Javascript Everywhere
Javascript EverywhereJavascript Everywhere
Javascript Everywhere
 
All you need to know about the JavaScript event loop
All you need to know about the JavaScript event loopAll you need to know about the JavaScript event loop
All you need to know about the JavaScript event loop
 
Coroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in PractiseCoroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in Practise
 
Coroutines talk ppt
Coroutines talk pptCoroutines talk ppt
Coroutines talk ppt
 
Async java8
Async java8Async java8
Async java8
 
Real Time Event Dispatcher
Real Time Event DispatcherReal Time Event Dispatcher
Real Time Event Dispatcher
 
Event loop
Event loopEvent loop
Event loop
 
연구자 및 교육자를 위한 계산 및 분석 플랫폼 설계 - PyCon KR 2015
연구자 및 교육자를 위한 계산 및 분석 플랫폼 설계 - PyCon KR 2015연구자 및 교육자를 위한 계산 및 분석 플랫폼 설계 - PyCon KR 2015
연구자 및 교육자를 위한 계산 및 분석 플랫폼 설계 - PyCon KR 2015
 
A Gentle Introduction to Event Loops
A Gentle Introduction to Event LoopsA Gentle Introduction to Event Loops
A Gentle Introduction to Event Loops
 
JavaScript Engines and Event Loop
JavaScript Engines and Event Loop JavaScript Engines and Event Loop
JavaScript Engines and Event Loop
 
Domains!
Domains!Domains!
Domains!
 
DevOps(3) : Ansible - (MOSG)
DevOps(3) : Ansible - (MOSG)DevOps(3) : Ansible - (MOSG)
DevOps(3) : Ansible - (MOSG)
 
Boom! Promises/A+ Was Born
Boom! Promises/A+ Was BornBoom! Promises/A+ Was Born
Boom! Promises/A+ Was Born
 
DJUGL - Django and AWS Lambda
DJUGL - Django and AWS LambdaDJUGL - Django and AWS Lambda
DJUGL - Django and AWS Lambda
 
node.js and native code extensions by example
node.js and native code extensions by examplenode.js and native code extensions by example
node.js and native code extensions by example
 

Viewers also liked

Clop 00237 a_co_p-2011_24mar2011
Clop 00237 a_co_p-2011_24mar2011Clop 00237 a_co_p-2011_24mar2011
Clop 00237 a_co_p-2011_24mar2011
vinillaxue
 
My Classes
My ClassesMy Classes
My Classes
Harry Copeland
 
La luna y la vaca
La luna y la vacaLa luna y la vaca
La luna y la vacaginasua
 
Alcinen heights intro
Alcinen heights introAlcinen heights intro
Alcinen heights introSimpony
 
Prezentangielskizrobiona 110509171449-phpapp02
Prezentangielskizrobiona 110509171449-phpapp02Prezentangielskizrobiona 110509171449-phpapp02
Prezentangielskizrobiona 110509171449-phpapp02
monia1989
 
CMC Teacher Education SIG Presentation; Mitchell
CMC Teacher Education SIG Presentation; MitchellCMC Teacher Education SIG Presentation; Mitchell
CMC Teacher Education SIG Presentation; Mitchell
CmcTchrEdSIG
 
La luna y la vaca
La luna y la vacaLa luna y la vaca
La luna y la vacaginasua
 
Melamine epichlorohydrin prepolymers syntheses and characterization
Melamine epichlorohydrin prepolymers syntheses and characterizationMelamine epichlorohydrin prepolymers syntheses and characterization
Melamine epichlorohydrin prepolymers syntheses and characterizationArif Yavuz Akartepe
 
Dualacy chap 2 winter
Dualacy chap 2 winterDualacy chap 2 winter
Dualacy chap 2 winterSimpony
 
Pregnancy four
Pregnancy fourPregnancy four
Pregnancy fourSimpony
 
Winter 1 cooke
Winter 1 cookeWinter 1 cooke
Winter 1 cookeSimpony
 
CMC Teacher Education SIG Presentation; Guichon
CMC Teacher Education SIG Presentation; GuichonCMC Teacher Education SIG Presentation; Guichon
CMC Teacher Education SIG Presentation; Guichon
CmcTchrEdSIG
 
Spring 3 Lillard
Spring 3 LillardSpring 3 Lillard
Spring 3 LillardSimpony
 
CMC Teacher Education SIG Presentation; O’Dowd
CMC Teacher Education SIG Presentation; O’DowdCMC Teacher Education SIG Presentation; O’Dowd
CMC Teacher Education SIG Presentation; O’Dowd
CmcTchrEdSIG
 
Winter 2 vega
Winter 2 vegaWinter 2 vega
Winter 2 vegaSimpony
 
IT Resource for Learning in TMU or Everywhere (20131115)
IT Resource for Learning in TMU or Everywhere (20131115)IT Resource for Learning in TMU or Everywhere (20131115)
IT Resource for Learning in TMU or Everywhere (20131115)Marian Wan
 
Summer 3 vega
Summer 3 vegaSummer 3 vega
Summer 3 vegaSimpony
 
Comas_Quinn_Barcelona2011
Comas_Quinn_Barcelona2011Comas_Quinn_Barcelona2011
Comas_Quinn_Barcelona2011
CmcTchrEdSIG
 
The Search For Alternative Energy
The Search For Alternative EnergyThe Search For Alternative Energy
The Search For Alternative Energy
tclythgoe84
 
CMC Teacher Education SIG Presentation; Antoniadou
CMC Teacher Education SIG Presentation; AntoniadouCMC Teacher Education SIG Presentation; Antoniadou
CMC Teacher Education SIG Presentation; Antoniadou
CmcTchrEdSIG
 

Viewers also liked (20)

Clop 00237 a_co_p-2011_24mar2011
Clop 00237 a_co_p-2011_24mar2011Clop 00237 a_co_p-2011_24mar2011
Clop 00237 a_co_p-2011_24mar2011
 
My Classes
My ClassesMy Classes
My Classes
 
La luna y la vaca
La luna y la vacaLa luna y la vaca
La luna y la vaca
 
Alcinen heights intro
Alcinen heights introAlcinen heights intro
Alcinen heights intro
 
Prezentangielskizrobiona 110509171449-phpapp02
Prezentangielskizrobiona 110509171449-phpapp02Prezentangielskizrobiona 110509171449-phpapp02
Prezentangielskizrobiona 110509171449-phpapp02
 
CMC Teacher Education SIG Presentation; Mitchell
CMC Teacher Education SIG Presentation; MitchellCMC Teacher Education SIG Presentation; Mitchell
CMC Teacher Education SIG Presentation; Mitchell
 
La luna y la vaca
La luna y la vacaLa luna y la vaca
La luna y la vaca
 
Melamine epichlorohydrin prepolymers syntheses and characterization
Melamine epichlorohydrin prepolymers syntheses and characterizationMelamine epichlorohydrin prepolymers syntheses and characterization
Melamine epichlorohydrin prepolymers syntheses and characterization
 
Dualacy chap 2 winter
Dualacy chap 2 winterDualacy chap 2 winter
Dualacy chap 2 winter
 
Pregnancy four
Pregnancy fourPregnancy four
Pregnancy four
 
Winter 1 cooke
Winter 1 cookeWinter 1 cooke
Winter 1 cooke
 
CMC Teacher Education SIG Presentation; Guichon
CMC Teacher Education SIG Presentation; GuichonCMC Teacher Education SIG Presentation; Guichon
CMC Teacher Education SIG Presentation; Guichon
 
Spring 3 Lillard
Spring 3 LillardSpring 3 Lillard
Spring 3 Lillard
 
CMC Teacher Education SIG Presentation; O’Dowd
CMC Teacher Education SIG Presentation; O’DowdCMC Teacher Education SIG Presentation; O’Dowd
CMC Teacher Education SIG Presentation; O’Dowd
 
Winter 2 vega
Winter 2 vegaWinter 2 vega
Winter 2 vega
 
IT Resource for Learning in TMU or Everywhere (20131115)
IT Resource for Learning in TMU or Everywhere (20131115)IT Resource for Learning in TMU or Everywhere (20131115)
IT Resource for Learning in TMU or Everywhere (20131115)
 
Summer 3 vega
Summer 3 vegaSummer 3 vega
Summer 3 vega
 
Comas_Quinn_Barcelona2011
Comas_Quinn_Barcelona2011Comas_Quinn_Barcelona2011
Comas_Quinn_Barcelona2011
 
The Search For Alternative Energy
The Search For Alternative EnergyThe Search For Alternative Energy
The Search For Alternative Energy
 
CMC Teacher Education SIG Presentation; Antoniadou
CMC Teacher Education SIG Presentation; AntoniadouCMC Teacher Education SIG Presentation; Antoniadou
CMC Teacher Education SIG Presentation; Antoniadou
 

Similar to Go Concurrency

A Channel Compendium
A Channel CompendiumA Channel Compendium
A Channel Compendium
Cloudflare
 
JVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in KotlinJVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in Kotlin
Andrey Breslav
 
Go Concurrency Patterns
Go Concurrency PatternsGo Concurrency Patterns
Go Concurrency Patterns
ElifTech
 
Elegant concurrency
Elegant concurrencyElegant concurrency
Elegant concurrency
Mosky Liu
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
Chetan Giridhar
 
Performance patterns
Performance patternsPerformance patterns
Performance patterns
Stoyan Stefanov
 
Aplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & JetpackAplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & Jetpack
Nelson Glauber Leal
 
Aplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & JetpackAplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & Jetpack
Nelson Glauber Leal
 
Aplicações Assíncronas no Android com Coroutines e Jetpack
Aplicações Assíncronas no Android com Coroutines e JetpackAplicações Assíncronas no Android com Coroutines e Jetpack
Aplicações Assíncronas no Android com Coroutines e Jetpack
Nelson Glauber Leal
 
Concurrency in go
Concurrency in goConcurrency in go
Concurrency in go
borderj
 
Golang Performance : microbenchmarks, profilers, and a war story
Golang Performance : microbenchmarks, profilers, and a war storyGolang Performance : microbenchmarks, profilers, and a war story
Golang Performance : microbenchmarks, profilers, and a war story
Aerospike
 
Torquebox OSCON Java 2011
Torquebox OSCON Java 2011Torquebox OSCON Java 2011
Torquebox OSCON Java 2011tobiascrawley
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in Golang
Bo-Yi Wu
 
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel ZikmundNDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
Karel Zikmund
 
JavaScript Async for Effortless UX
JavaScript Async for Effortless UXJavaScript Async for Effortless UX
JavaScript Async for Effortless UX
재석 강
 
Writing Docker monitoring agent with Go
Writing Docker monitoring agent with GoWriting Docker monitoring agent with Go
Writing Docker monitoring agent with Go
Naoki AINOYA
 
Concurrency in Golang
Concurrency in GolangConcurrency in Golang
Concurrency in Golang
Oliver N
 
Concurrency at the Database Layer
Concurrency at the Database Layer Concurrency at the Database Layer
Concurrency at the Database Layer
mcwilson1
 
Writing Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & AkkaWriting Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & Akka
Yardena Meymann
 
Getting property based testing to work after struggling for 3 years
Getting property based testing to work after struggling for 3 yearsGetting property based testing to work after struggling for 3 years
Getting property based testing to work after struggling for 3 years
Saurabh Nanda
 

Similar to Go Concurrency (20)

A Channel Compendium
A Channel CompendiumA Channel Compendium
A Channel Compendium
 
JVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in KotlinJVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in Kotlin
 
Go Concurrency Patterns
Go Concurrency PatternsGo Concurrency Patterns
Go Concurrency Patterns
 
Elegant concurrency
Elegant concurrencyElegant concurrency
Elegant concurrency
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
 
Performance patterns
Performance patternsPerformance patterns
Performance patterns
 
Aplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & JetpackAplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & Jetpack
 
Aplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & JetpackAplicações assíncronas no Android com
Coroutines & Jetpack
Aplicações assíncronas no Android com
Coroutines & Jetpack
 
Aplicações Assíncronas no Android com Coroutines e Jetpack
Aplicações Assíncronas no Android com Coroutines e JetpackAplicações Assíncronas no Android com Coroutines e Jetpack
Aplicações Assíncronas no Android com Coroutines e Jetpack
 
Concurrency in go
Concurrency in goConcurrency in go
Concurrency in go
 
Golang Performance : microbenchmarks, profilers, and a war story
Golang Performance : microbenchmarks, profilers, and a war storyGolang Performance : microbenchmarks, profilers, and a war story
Golang Performance : microbenchmarks, profilers, and a war story
 
Torquebox OSCON Java 2011
Torquebox OSCON Java 2011Torquebox OSCON Java 2011
Torquebox OSCON Java 2011
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in Golang
 
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel ZikmundNDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
 
JavaScript Async for Effortless UX
JavaScript Async for Effortless UXJavaScript Async for Effortless UX
JavaScript Async for Effortless UX
 
Writing Docker monitoring agent with Go
Writing Docker monitoring agent with GoWriting Docker monitoring agent with Go
Writing Docker monitoring agent with Go
 
Concurrency in Golang
Concurrency in GolangConcurrency in Golang
Concurrency in Golang
 
Concurrency at the Database Layer
Concurrency at the Database Layer Concurrency at the Database Layer
Concurrency at the Database Layer
 
Writing Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & AkkaWriting Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & Akka
 
Getting property based testing to work after struggling for 3 years
Getting property based testing to work after struggling for 3 yearsGetting property based testing to work after struggling for 3 years
Getting property based testing to work after struggling for 3 years
 

More from Cloudflare

Succeeding with Secure Access Service Edge (SASE)
Succeeding with Secure Access Service Edge (SASE)Succeeding with Secure Access Service Edge (SASE)
Succeeding with Secure Access Service Edge (SASE)
Cloudflare
 
Close your security gaps and get 100% of your traffic protected with Cloudflare
Close your security gaps and get 100% of your traffic protected with CloudflareClose your security gaps and get 100% of your traffic protected with Cloudflare
Close your security gaps and get 100% of your traffic protected with Cloudflare
Cloudflare
 
Why you should replace your d do s hardware appliance
Why you should replace your d do s hardware applianceWhy you should replace your d do s hardware appliance
Why you should replace your d do s hardware appliance
Cloudflare
 
Don't Let Bots Ruin Your Holiday Business - Snackable Webinar
Don't Let Bots Ruin Your Holiday Business - Snackable WebinarDon't Let Bots Ruin Your Holiday Business - Snackable Webinar
Don't Let Bots Ruin Your Holiday Business - Snackable Webinar
Cloudflare
 
Why Zero Trust Architecture Will Become the New Normal in 2021
Why Zero Trust Architecture Will Become the New Normal in 2021Why Zero Trust Architecture Will Become the New Normal in 2021
Why Zero Trust Architecture Will Become the New Normal in 2021
Cloudflare
 
HARTMANN and Cloudflare Learn how healthcare providers can build resilient in...
HARTMANN and Cloudflare Learn how healthcare providers can build resilient in...HARTMANN and Cloudflare Learn how healthcare providers can build resilient in...
HARTMANN and Cloudflare Learn how healthcare providers can build resilient in...
Cloudflare
 
Zero trust for everybody: 3 ways to get there fast
Zero trust for everybody: 3 ways to get there fastZero trust for everybody: 3 ways to get there fast
Zero trust for everybody: 3 ways to get there fast
Cloudflare
 
LendingTree and Cloudflare: Ensuring zero trade-off between security and cust...
LendingTree and Cloudflare: Ensuring zero trade-off between security and cust...LendingTree and Cloudflare: Ensuring zero trade-off between security and cust...
LendingTree and Cloudflare: Ensuring zero trade-off between security and cust...
Cloudflare
 
Network Transformation: What it is, and how it’s helping companies stay secur...
Network Transformation: What it is, and how it’s helping companies stay secur...Network Transformation: What it is, and how it’s helping companies stay secur...
Network Transformation: What it is, and how it’s helping companies stay secur...
Cloudflare
 
Scaling service provider business with DDoS-mitigation-as-a-service
Scaling service provider business with DDoS-mitigation-as-a-serviceScaling service provider business with DDoS-mitigation-as-a-service
Scaling service provider business with DDoS-mitigation-as-a-service
Cloudflare
 
Application layer attack trends through the lens of Cloudflare data
Application layer attack trends through the lens of Cloudflare dataApplication layer attack trends through the lens of Cloudflare data
Application layer attack trends through the lens of Cloudflare data
Cloudflare
 
Recent DDoS attack trends, and how you should respond
Recent DDoS attack trends, and how you should respondRecent DDoS attack trends, and how you should respond
Recent DDoS attack trends, and how you should respond
Cloudflare
 
Cybersecurity 2020 threat landscape and its implications (AMER)
Cybersecurity 2020 threat landscape and its implications (AMER)Cybersecurity 2020 threat landscape and its implications (AMER)
Cybersecurity 2020 threat landscape and its implications (AMER)
Cloudflare
 
Strengthening security posture for modern-age SaaS providers
Strengthening security posture for modern-age SaaS providersStrengthening security posture for modern-age SaaS providers
Strengthening security posture for modern-age SaaS providers
Cloudflare
 
Kentik and Cloudflare Partner to Mitigate Advanced DDoS Attacks
Kentik and Cloudflare Partner to Mitigate Advanced DDoS AttacksKentik and Cloudflare Partner to Mitigate Advanced DDoS Attacks
Kentik and Cloudflare Partner to Mitigate Advanced DDoS Attacks
Cloudflare
 
Stopping DDoS Attacks in North America
Stopping DDoS Attacks in North AmericaStopping DDoS Attacks in North America
Stopping DDoS Attacks in North America
Cloudflare
 
It’s 9AM... Do you know what’s happening on your network?
It’s 9AM... Do you know what’s happening on your network?It’s 9AM... Do you know what’s happening on your network?
It’s 9AM... Do you know what’s happening on your network?
Cloudflare
 
Cyber security fundamentals (simplified chinese)
Cyber security fundamentals (simplified chinese)Cyber security fundamentals (simplified chinese)
Cyber security fundamentals (simplified chinese)
Cloudflare
 
Bring speed and security to the intranet with cloudflare for teams
Bring speed and security to the intranet with cloudflare for teamsBring speed and security to the intranet with cloudflare for teams
Bring speed and security to the intranet with cloudflare for teams
Cloudflare
 
Accelerate your digital transformation
Accelerate your digital transformationAccelerate your digital transformation
Accelerate your digital transformation
Cloudflare
 

More from Cloudflare (20)

Succeeding with Secure Access Service Edge (SASE)
Succeeding with Secure Access Service Edge (SASE)Succeeding with Secure Access Service Edge (SASE)
Succeeding with Secure Access Service Edge (SASE)
 
Close your security gaps and get 100% of your traffic protected with Cloudflare
Close your security gaps and get 100% of your traffic protected with CloudflareClose your security gaps and get 100% of your traffic protected with Cloudflare
Close your security gaps and get 100% of your traffic protected with Cloudflare
 
Why you should replace your d do s hardware appliance
Why you should replace your d do s hardware applianceWhy you should replace your d do s hardware appliance
Why you should replace your d do s hardware appliance
 
Don't Let Bots Ruin Your Holiday Business - Snackable Webinar
Don't Let Bots Ruin Your Holiday Business - Snackable WebinarDon't Let Bots Ruin Your Holiday Business - Snackable Webinar
Don't Let Bots Ruin Your Holiday Business - Snackable Webinar
 
Why Zero Trust Architecture Will Become the New Normal in 2021
Why Zero Trust Architecture Will Become the New Normal in 2021Why Zero Trust Architecture Will Become the New Normal in 2021
Why Zero Trust Architecture Will Become the New Normal in 2021
 
HARTMANN and Cloudflare Learn how healthcare providers can build resilient in...
HARTMANN and Cloudflare Learn how healthcare providers can build resilient in...HARTMANN and Cloudflare Learn how healthcare providers can build resilient in...
HARTMANN and Cloudflare Learn how healthcare providers can build resilient in...
 
Zero trust for everybody: 3 ways to get there fast
Zero trust for everybody: 3 ways to get there fastZero trust for everybody: 3 ways to get there fast
Zero trust for everybody: 3 ways to get there fast
 
LendingTree and Cloudflare: Ensuring zero trade-off between security and cust...
LendingTree and Cloudflare: Ensuring zero trade-off between security and cust...LendingTree and Cloudflare: Ensuring zero trade-off between security and cust...
LendingTree and Cloudflare: Ensuring zero trade-off between security and cust...
 
Network Transformation: What it is, and how it’s helping companies stay secur...
Network Transformation: What it is, and how it’s helping companies stay secur...Network Transformation: What it is, and how it’s helping companies stay secur...
Network Transformation: What it is, and how it’s helping companies stay secur...
 
Scaling service provider business with DDoS-mitigation-as-a-service
Scaling service provider business with DDoS-mitigation-as-a-serviceScaling service provider business with DDoS-mitigation-as-a-service
Scaling service provider business with DDoS-mitigation-as-a-service
 
Application layer attack trends through the lens of Cloudflare data
Application layer attack trends through the lens of Cloudflare dataApplication layer attack trends through the lens of Cloudflare data
Application layer attack trends through the lens of Cloudflare data
 
Recent DDoS attack trends, and how you should respond
Recent DDoS attack trends, and how you should respondRecent DDoS attack trends, and how you should respond
Recent DDoS attack trends, and how you should respond
 
Cybersecurity 2020 threat landscape and its implications (AMER)
Cybersecurity 2020 threat landscape and its implications (AMER)Cybersecurity 2020 threat landscape and its implications (AMER)
Cybersecurity 2020 threat landscape and its implications (AMER)
 
Strengthening security posture for modern-age SaaS providers
Strengthening security posture for modern-age SaaS providersStrengthening security posture for modern-age SaaS providers
Strengthening security posture for modern-age SaaS providers
 
Kentik and Cloudflare Partner to Mitigate Advanced DDoS Attacks
Kentik and Cloudflare Partner to Mitigate Advanced DDoS AttacksKentik and Cloudflare Partner to Mitigate Advanced DDoS Attacks
Kentik and Cloudflare Partner to Mitigate Advanced DDoS Attacks
 
Stopping DDoS Attacks in North America
Stopping DDoS Attacks in North AmericaStopping DDoS Attacks in North America
Stopping DDoS Attacks in North America
 
It’s 9AM... Do you know what’s happening on your network?
It’s 9AM... Do you know what’s happening on your network?It’s 9AM... Do you know what’s happening on your network?
It’s 9AM... Do you know what’s happening on your network?
 
Cyber security fundamentals (simplified chinese)
Cyber security fundamentals (simplified chinese)Cyber security fundamentals (simplified chinese)
Cyber security fundamentals (simplified chinese)
 
Bring speed and security to the intranet with cloudflare for teams
Bring speed and security to the intranet with cloudflare for teamsBring speed and security to the intranet with cloudflare for teams
Bring speed and security to the intranet with cloudflare for teams
 
Accelerate your digital transformation
Accelerate your digital transformationAccelerate your digital transformation
Accelerate your digital transformation
 

Recently uploaded

FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
CatarinaPereira64715
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
Fwdays
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
Abida Shariff
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 

Recently uploaded (20)

FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 

Go Concurrency

  • 1. Go Concurrency March 27, 2013 John Graham-Cumming www.cloudflare.com!
  • 2. Fundamentals •  goroutines •  Very lightweight processes •  All scheduling handled internally by the Go runtime •  Unless you are CPU bound you do not have to think about scheduling •  Channel-based communication •  The right way for goroutines to talk to each other •  Synchronization Primitives •  For when a channel is too heavyweight •  Not covered in this talk www.cloudflare.com!
  • 3. goroutines •  “Lightweight” •  Starting 10,000 goroutines on my MacBook Pro took 22ms •  Allocated memory increased by 3,014,000 bytes (301 bytes per goroutine) •  https://gist.github.com/jgrahamc/5253020 •  Not unusual at CloudFlare to have a single Go program running 10,000s of goroutines with 1,000,000s of goroutines created during life program. •  So, go yourFunc() as much as you like. www.cloudflare.com!
  • 4. Channels •  Quick syntax review c := make(chan bool)– Makes an unbuffered channel of bools c <- x – Sends a value on the channel <- c – Waits to receive a value on the channel x = <- c – Waits to receive a value and stores it in x x, ok = <- c – Waits to receive a value; ok will be false if channel is closed and empty. www.cloudflare.com!
  • 5. Unbuffered channels are best •  They provide both communication and synchronization func from(connection chan int) {! connection <- rand.Intn(100)! }! ! func to(connection chan int) {! i := <- connection! fmt.Printf("Someone sent me %dn", i)! }! ! func main() {! cpus := runtime.NumCPU()! runtime.GOMAXPROCS(cpus)! ! connection := make(chan int)! go from(connection)! go to(connection)! }! www.cloudflare.com!
  • 6. Using channels for signaling (1) •  Sometimes just closing a channel is enough c := make(chan bool)! ! go func() {! !// ... do some stuff! !close(c)! }()! ! // ... do some other stuff! <- c! www.cloudflare.com!
  • 7. Using channels for signaling (2) •  Close a channel to coordinate multiple goroutines func worker(start chan bool) {! <- start! // ... do stuff! }! ! func main() {! start := make(chan bool)! ! for i := 0; i < 100; i++ {! go worker(start)! }! ! close(start)! ! // ... all workers running now! }! www.cloudflare.com!
  • 8. Select •  Select statement enables sending/receiving on multiple channels at once select {! case x := <- somechan:! // ... do stuff with x! ! case y, ok := <- someOtherchan:! // ... do stuff with y! // check ok to see if someOtherChan! // is closed! ! case outputChan <- z:! // ... ok z was sent! ! default:! // ... no one wants to communicate! }! www.cloudflare.com!
  • 9. Common idiom: for/select! for {! select {! case x := <- somechan:! // ... do stuff with x! ! case y, ok := <- someOtherchan:! // ... do stuff with y! // check ok to see if someOtherChan! // is closed! ! case outputChan <- z:! // ... ok z was sent! ! default:! // ... no one wants to communicate! }! }! www.cloudflare.com!
  • 10. Using channels for signaling (4) •  Close a channel to terminate multiple goroutines func worker(die chan bool) {! for {! select {! // ... do stuff cases! case <- die: ! return! }! }! }! ! func main() {! die := make(chan bool)! for i := 0; i < 100; i++ {! go worker(die)! }! close(die)! }! www.cloudflare.com!
  • 11. Using channels for signaling (5) •  Terminate a goroutine and verify termination func worker(die chan bool) {! for {! select {! // ... do stuff cases! case <- die:! // ... do termination tasks ! die <- true! return! }! }! }! func main() {! die := make(chan bool)! go worker(die)! die <- true! <- die! }! www.cloudflare.com!
  • 12. Example: unique ID service •  Just receive from id to get a unique ID •  Safe to share id channel across routines id := make(chan string)! ! go func() {! var counter int64 = 0! for {! id <- fmt.Sprintf("%x", counter)! counter += 1! }! }()! ! x := <- id // x will be 1! x = <- id // x will be 2! www.cloudflare.com!
  • 13. Example: memory recycler func recycler(give, get chan []byte) {! q := new(list.List)! ! for {! if q.Len() == 0 {! q.PushFront(make([]byte, 100))! }! ! e := q.Front()! ! select {! case s := <-give:! q.PushFront(s[:0])! ! case get <- e.Value.([]byte):! q.Remove(e)! }! }! }! www.cloudflare.com!
  • 14. Timeout func worker(start chan bool) {! for {! !timeout := time.After(30 * time.Second)! !select {! // ... do some stuff! ! case <- timeout:! return! }! func worker(start chan bool) {! }! timeout := time.After(30 * time.Second)! }! for {! !select {! // ... do some stuff! ! case <- timeout:! return! }! }! }! www.cloudflare.com!
  • 15. Heartbeat func worker(start chan bool) {! heartbeat := time.Tick(30 * time.Second)! for {! !select {! // ... do some stuff! ! case <- heartbeat:! // ... do heartbeat stuff! }! }! }! www.cloudflare.com!
  • 16. Example: network multiplexor •  Multiple goroutines can send on the same channel func worker(messages chan string) {! for {! var msg string // ... generate a message! messages <- msg! }! }! func main() {! messages := make(chan string)! conn, _ := net.Dial("tcp", "example.com")! ! for i := 0; i < 100; i++ {! go worker(messages)! }! for {! msg := <- messages! conn.Write([]byte(msg))! }! }! www.cloudflare.com!
  • 17. Example: first of N •  Dispatch requests and get back the first one to complete type response struct {! resp *http.Response! url string! }! ! func get(url string, r chan response ) {! if resp, err := http.Get(url); err == nil {! r <- response{resp, url}! }! }! ! func main() {! first := make(chan response)! for _, url := range []string{"http://code.jquery.com/jquery-1.9.1.min.js",! "http://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js",! "http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js",! "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js"} {! go get(url, first)! }! ! r := <- first! // ... do something! }! www.cloudflare.com!
  • 18. range! •  Can be used to consume all values from a channel func generator(strings chan string) {! strings <- "Five hour's New York jet lag"! strings <- "and Cayce Pollard wakes in Camden Town"! strings <- "to the dire and ever-decreasing circles"! strings <- "of disrupted circadian rhythm."! close(strings)! }! ! func main() {! strings := make(chan string)! go generator(strings)! ! for s := range strings {! fmt.Printf("%s ", s)! }! fmt.Printf("n");! }! www.cloudflare.com!
  • 19. Passing a ‘response’ channel type work struct {! url string! resp chan *http.Response! }! ! func getter(w chan work) {! for {! do := <- w! resp, _ := http.Get(do.url)! do.resp <- resp! }! }! ! func main() {! w := make(chan work)! ! go getter(w)! ! resp := make(chan *http.Response)! w <- work{"http://cdnjs.cloudflare.com/jquery/1.9.1/jquery.min.js",! resp}! ! r := <- resp! }! www.cloudflare.com!
  • 20. Buffered channels •  Can be useful to create queues •  But make reasoning about concurrency more difficult c := make(chan bool, 100) ! www.cloudflare.com!
  • 21. Example: an HTTP load balancer •  Limited number of HTTP clients can make requests for URLs •  Unlimited number of goroutines need to request URLs and get responses •  Solution: an HTTP request load balancer www.cloudflare.com!
  • 22. A URL getter type job struct {! url string! resp chan *http.Response! }! ! type worker struct {! jobs chan *job! count int! }! ! func (w *worker) getter(done chan *worker) {! for {! j := <- w.jobs! resp, _ := http.Get(j.url)! j.resp <- resp! done <- w! }! }! www.cloudflare.com!
  • 23. A way to get URLs func get(jobs chan *job, url string, answer chan string) {! resp := make(chan *http.Response)! jobs <- &job{url, resp}! r := <- resp! answer <- r.Request.URL.String()! }! ! func main() {! jobs := balancer(10, 10)! answer := make(chan string)! for {! var url string! if _, err := fmt.Scanln(&url); err != nil {! break! }! go get(jobs, url, answer)! }! for u := range answer {! fmt.Printf("%sn", u)! }! }! www.cloudflare.com!
  • 24. A load balancer func balancer(count int, depth int) chan *job {! jobs := make(chan *job)! done := make(chan *worker)! workers := make([]*worker, count)! ! for i := 0; i < count; i++ {! workers[i] = &worker{make(chan *job,
 depth), 0}! go workers[i].getter(done)! }! ! ! select {! go func() {! case j := <- jobsource:! for {! free.jobs <- j! var free *worker! free.count++! min := depth! ! for _, w := range workers {! case w := <- done:! if w.count < min {! w.count—! free = w! }! min = w.count! }! }! }()! }! ! ! return jobs! var jobsource chan *job! }! if free != nil {! jobsource = jobs! }! www.cloudflare.com!
  • 25. Top 500 web sites loaded www.cloudflare.com!
  • 26. THANKS The Go Way: “small sequential pieces joined by channels” www.cloudflare.com!