The async/await concurrency pattern in Golang

The await/async
concurrency pattern
January, 29th - Torino, Toolbox Coworking
…in Golang
Matteo Madeddu
Github: @made2591
Role: Devops, AWS, miscellanea
matteo.madeddu@gmail.com
Work: enerbrain.com
Blog: madeddu.xyz
A bit of history
Version 1.0
released
March, 2012
Go first appeared
in Google,
2007
November, 2009
Google announce Golang
to the worldwide
community
June, 2017
I released a
go-perceptron
on Github
Golang Developer Group
begins in Turin
January, 2020
2020
The community
grows!
The async/await concurrency pattern in Golang
The async/await concurrency pattern in Golang
github.com/docker/engine
github.com/docker/engine
github.com/kubernetes/kubernetes
github.com/docker/engine
github.com/kubernetes/kubernetes
github.com/hashicorp/terraform
github.com/docker/engine
github.com/kubernetes/kubernetes
github.com/hashicorp/terraform
github.com/prometheus/prometheus
github.com/docker/engine
github.com/kubernetes/kubernetes
github.com/hashicorp/terraform
github.com/grafana/grafana
github.com/prometheus/prometheus
github.com/docker/engine
github.com/kubernetes/kubernetes
github.com/hashicorp/terraform
github.com/gohugoio/hugo
github.com/grafana/grafana
github.com/prometheus/prometheus
The async/await concurrency pattern in Golang
it’s statically typed
it’s statically typed
it’s compiled
it’s statically typed
it’s compiled
and provide
interesting concurrency primitives to final users
The async/await concurrency pattern in Golang
Hello World
package main
import "fmt"
func main() {
fmt.Println("hello world")
}
package main
import "fmt"
func main() {
var a = "initial"
fmt.Println(a) # initial
var b, c int = 1, 2
fmt.Println(a, b) # 1, 2
var d = true
fmt.Println(d) # true
var e int
fmt.Println(e) # 0
f := "apple"
fmt.Println(f) # apple
}
Concurrency
Dealing with many things at once.
Concurrency
Dealing with many things at once.
Parallelism
Doing many things at once.
Concurrency is the composition of independently
executing processes, while parallelism is the
simultaneous execution of (possibly related)
computations.
Introducing
goroutines
package main
import (
"fmt"
"time"
)
func f(from string) {
for i := 0; i < 3; i++ {
fmt.Println(from, ":", i)
}
}
func main() {
f("direct")
go f("goroutine")
go func(msg string) {
fmt.Println(msg)
}("going")
time.Sleep(time.Second)
fmt.Println("done")
}
Introducing
goroutines
package main
import (
"fmt"
"time"
)
func f(from string) {
for i := 0; i < 3; i++ {
fmt.Println(from, ":", i)
}
}
func main() {
f("direct")
go f("goroutine")
go func(msg string) {
fmt.Println(msg)
}("going")
time.Sleep(time.Second)
fmt.Println("done")
}
# standard function call
Introducing
goroutines
package main
import (
"fmt"
"time"
)
func f(from string) {
for i := 0; i < 3; i++ {
fmt.Println(from, ":", i)
}
}
func main() {
f("direct")
go f("goroutine")
go func(msg string) {
fmt.Println(msg)
}("going")
time.Sleep(time.Second)
fmt.Println("done")
}
# standard function call
# to invoke this function
in a goroutine, use go f(s).
This new goroutine will
execute concurrently with
the calling one.
When we run this program, we see
the output of the blocking call
first, then the interleaved output of
the two goroutines.
This interleaving reflects the
goroutines being run concurrently
by the Go runtime.
Introducing
channels
Channels are the pipes that connect
concurrent goroutines.
package main
import "fmt"
func main() {
messages := make(chan string)
go func() { messages <- "ping" }()
msg := <-messages
fmt.Println(msg)
}
Introducing
channels
package main
import "fmt"
func main() {
messages := make(chan string)
go func() { messages <- "ping" }()
msg := <-messages
fmt.Println(msg)
}
# channels are typed by the
values they convey
Introducing
channels
package main
import "fmt"
func main() {
messages := make(chan string)
go func() { messages <- "ping" }()
msg := <-messages
fmt.Println(msg)
}
# channels are typed by the
values they convey
# when we run the program
the "ping" message is
successfully passed from one
goroutine to another via our
channel.
Introducing
channels
By default sends and receives block until
both the sender and receiver are ready.
This property allowed us to wait at the end
of our program for the "ping" message
without having to use any other
synchronization.
Philosophically, the idea behind Go is:
Don't communicate by sharing
memory; share memory by
communicating.
The await/async
concurrency pattern
The await/async
is special syntax to work with
Promises in a more comfortable way
Promise
A promise is a special JavaScript
object that let links production and
consuming code
async
Before a function means “this function
always returns a Promise”
Promise
A promise is a special JavaScript
object that let links production and
consuming code
async
Before a function means “this function
always returns a Promise”
await
Works only inside async function and makes
JavaScript wait until that Promise settles
and returns its result
Promise
A promise is a special JavaScript
object that let links production and
consuming code
const sleep = require('util').promisify(setTimeout)
async function myAsyncFunction() {
await sleep(2000)
return 2
};
(async function() {
const result = await myAsyncFunction();
// outputs `2` after two seconds
console.log(result);
})();
// ... package main and imports
func myAsyncFunction() <-chan int32 {
r := make(chan int32)
go func() {
defer close(r)
// work to be completed
time.Sleep(time.Second * 2)
r <- 2
}()
return r
}
func main() {
r := <-myAsyncFunction()
// outputs `2` after two seconds
fmt.Println(r)
}
Promise.all()
const myAsyncFunction = (s) => {
return new Promise((resolve) => {
setTimeout(() => resolve(s), 2000);
})
};
(async function() {
const result = await Promise.all([
myAsyncFunction(2),
myAsyncFunction(3)
]);
// outputs `2, 3` after two seconds
console.log(result);
})();
// ... package main and imports
func myAsyncFunction() <-chan int32 {
r := make(chan int32)
go func() {
defer close(r)
// work to be completed
time.Sleep(time.Second * 2)
r <- 2
}()
return r
}
func main() {
firstChannel, secondChannel :=
myAsyncFunction(2), myAsyncFunction(3)
first, second := <-firstChannel, <-secondChannel
// outputs `2, 3` after two seconds
fmt.Println(first, second)
}
The cool thing about channels is that
you can use Go's select statement
to implement concurrency patterns
and wait on multiple channel
operations.
Promise.race()
const myAsyncFunction = (s) => {
return new Promise((resolve) => {
setTimeout(() => resolve(s), 2000);
})
};
(async function() {
const result = await Promise.race([
myAsyncFunction(2),
myAsyncFunction(3)
]);
// outputs `2` or `3` after two seconds
console.log(result);
})();
// ... package main and imports
func myAsyncFunction() <-chan int32 {
r := make(chan int32)
go func() {
defer close(r)
// work to be completed
time.Sleep(time.Second * 2)
r <- 2
}()
return r
}
func main() {
var r int32
select {
case r = <-myAsyncFunction(2)
case r = <-myAsyncFunction(3)
}
// outputs `2` or `3` after two seconds
fmt.Println(r)
}
https://tour.golang.org/
https://madeddu.xyz/posts/go-async-await/
https://blog.golang.org/concurrency-is-not-parallelism
https://gobyexample.com/non-blocking-channel-operations
Thank you!
Matteo Madeddu
Github: @made2591
Role: Devops, AWS, miscellanea
matteo.madeddu@gmail.com
Work: enerbrain.com
Blog: madeddu.xyz
1 of 50

Recommended

Go concurrency by
Go concurrencyGo concurrency
Go concurrencysiuyin
981 views35 slides
Concurrency in Golang by
Concurrency in GolangConcurrency in Golang
Concurrency in GolangOliver N
847 views40 slides
Kotlin Coroutines. Flow is coming by
Kotlin Coroutines. Flow is comingKotlin Coroutines. Flow is coming
Kotlin Coroutines. Flow is comingKirill Rozov
3.3K views61 slides
Concurrency in go by
Concurrency in goConcurrency in go
Concurrency in goborderj
2.7K views27 slides
Concurrency with Go by
Concurrency with GoConcurrency with Go
Concurrency with GoFrank Müller
147 views71 slides
Music as data by
Music as dataMusic as data
Music as dataJohn Vlachoyiannis
704 views79 slides

More Related Content

What's hot

Puppet User Group Presentation - 15 March 2012 by
Puppet User Group Presentation - 15 March 2012Puppet User Group Presentation - 15 March 2012
Puppet User Group Presentation - 15 March 2012Walter Heck
1.6K views12 slides
Performance testing of microservices in Action by
Performance testing of microservices in ActionPerformance testing of microservices in Action
Performance testing of microservices in ActionAlexander Kachur
885 views57 slides
ops300 Week8 gre by
ops300 Week8 greops300 Week8 gre
ops300 Week8 gretrayyoo
71 views8 slides
Go on! by
Go on!Go on!
Go on!Vadim Petrov
25 views42 slides
Coding in GO - GDG SL - NSBM by
Coding in GO - GDG SL - NSBMCoding in GO - GDG SL - NSBM
Coding in GO - GDG SL - NSBMRaveen Perera
191 views23 slides
Scaling FastAGI Applications with Go by
Scaling FastAGI Applications with GoScaling FastAGI Applications with Go
Scaling FastAGI Applications with GoDigium
1.8K views30 slides

What's hot(20)

Puppet User Group Presentation - 15 March 2012 by Walter Heck
Puppet User Group Presentation - 15 March 2012Puppet User Group Presentation - 15 March 2012
Puppet User Group Presentation - 15 March 2012
Walter Heck1.6K views
Performance testing of microservices in Action by Alexander Kachur
Performance testing of microservices in ActionPerformance testing of microservices in Action
Performance testing of microservices in Action
Alexander Kachur885 views
ops300 Week8 gre by trayyoo
ops300 Week8 greops300 Week8 gre
ops300 Week8 gre
trayyoo71 views
Coding in GO - GDG SL - NSBM by Raveen Perera
Coding in GO - GDG SL - NSBMCoding in GO - GDG SL - NSBM
Coding in GO - GDG SL - NSBM
Raveen Perera191 views
Scaling FastAGI Applications with Go by Digium
Scaling FastAGI Applications with GoScaling FastAGI Applications with Go
Scaling FastAGI Applications with Go
Digium1.8K views
Golang concurrency design by Hyejong
Golang concurrency designGolang concurrency design
Golang concurrency design
Hyejong1.1K views
Cotap Tech Talks: Keith Lazuka, Digital Communication using Sound and Swift by Evan Owen
Cotap Tech Talks: Keith Lazuka, Digital Communication using Sound and SwiftCotap Tech Talks: Keith Lazuka, Digital Communication using Sound and Swift
Cotap Tech Talks: Keith Lazuka, Digital Communication using Sound and Swift
Evan Owen537 views
Go Containers by jgrahamc
Go ContainersGo Containers
Go Containers
jgrahamc3.7K views
Demystifying the Go Scheduler by matthewrdale
Demystifying the Go SchedulerDemystifying the Go Scheduler
Demystifying the Go Scheduler
matthewrdale7.6K views
Concurrency in Go by Denys Goldiner.pdf by Denys Goldiner
Concurrency in Go by Denys Goldiner.pdfConcurrency in Go by Denys Goldiner.pdf
Concurrency in Go by Denys Goldiner.pdf
Denys Goldiner195 views
Perl - laziness, impatience, hubris, and one liners by Kirk Kimmel
Perl - laziness, impatience, hubris, and one linersPerl - laziness, impatience, hubris, and one liners
Perl - laziness, impatience, hubris, and one liners
Kirk Kimmel2.3K views
Ntp cheat sheet by csystemltd
Ntp cheat sheetNtp cheat sheet
Ntp cheat sheet
csystemltd201 views

Similar to The async/await concurrency pattern in Golang

Something about Golang by
Something about GolangSomething about Golang
Something about GolangAnton Arhipov
1.5K views69 slides
Geeks Anonymes - Le langage Go by
Geeks Anonymes - Le langage GoGeeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes
237 views42 slides
The Ring programming language version 1.7 book - Part 82 of 196 by
The Ring programming language version 1.7 book - Part 82 of 196The Ring programming language version 1.7 book - Part 82 of 196
The Ring programming language version 1.7 book - Part 82 of 196Mahmoud Samir Fayed
10 views10 slides
golang_getting_started.pptx by
golang_getting_started.pptxgolang_getting_started.pptx
golang_getting_started.pptxGuy Komari
99 views55 slides
Os lab final by
Os lab finalOs lab final
Os lab finalLakshmiSarvani6
143 views29 slides
Talk Python To Me: Stream Processing in your favourite Language with Beam on ... by
Talk Python To Me: Stream Processing in your favourite Language with Beam on ...Talk Python To Me: Stream Processing in your favourite Language with Beam on ...
Talk Python To Me: Stream Processing in your favourite Language with Beam on ...Aljoscha Krettek
273 views43 slides

Similar to The async/await concurrency pattern in Golang(20)

Something about Golang by Anton Arhipov
Something about GolangSomething about Golang
Something about Golang
Anton Arhipov1.5K views
Geeks Anonymes - Le langage Go by Geeks Anonymes
Geeks Anonymes - Le langage GoGeeks Anonymes - Le langage Go
Geeks Anonymes - Le langage Go
Geeks Anonymes237 views
The Ring programming language version 1.7 book - Part 82 of 196 by Mahmoud Samir Fayed
The Ring programming language version 1.7 book - Part 82 of 196The Ring programming language version 1.7 book - Part 82 of 196
The Ring programming language version 1.7 book - Part 82 of 196
golang_getting_started.pptx by Guy Komari
golang_getting_started.pptxgolang_getting_started.pptx
golang_getting_started.pptx
Guy Komari99 views
Talk Python To Me: Stream Processing in your favourite Language with Beam on ... by Aljoscha Krettek
Talk Python To Me: Stream Processing in your favourite Language with Beam on ...Talk Python To Me: Stream Processing in your favourite Language with Beam on ...
Talk Python To Me: Stream Processing in your favourite Language with Beam on ...
Aljoscha Krettek273 views
The GO Language : From Beginners to Gophers by Alessandro Sanino
The GO Language : From Beginners to GophersThe GO Language : From Beginners to Gophers
The GO Language : From Beginners to Gophers
Alessandro Sanino384 views
Job Queue in Golang by Bo-Yi Wu
Job Queue in GolangJob Queue in Golang
Job Queue in Golang
Bo-Yi Wu22.3K views
Pablo Magaz | ECMAScript 2018 y más allá | Codemotion Madrid 2018 by Codemotion
Pablo Magaz | ECMAScript 2018 y más allá | Codemotion Madrid 2018Pablo Magaz | ECMAScript 2018 y más allá | Codemotion Madrid 2018
Pablo Magaz | ECMAScript 2018 y más allá | Codemotion Madrid 2018
Codemotion140 views
Flink Forward Berlin 2017: Aljoscha Krettek - Talk Python to me: Stream Proce... by Flink Forward
Flink Forward Berlin 2017: Aljoscha Krettek - Talk Python to me: Stream Proce...Flink Forward Berlin 2017: Aljoscha Krettek - Talk Python to me: Stream Proce...
Flink Forward Berlin 2017: Aljoscha Krettek - Talk Python to me: Stream Proce...
Flink Forward1.1K views
Golang basics for Java developers - Part 1 by Robert Stern
Golang basics for Java developers - Part 1Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1
Robert Stern1.3K views
Introduction to MPI by yaman dua
Introduction to MPIIntroduction to MPI
Introduction to MPI
yaman dua293 views
Introduction to go by Jaehue Jang
Introduction to goIntroduction to go
Introduction to go
Jaehue Jang2.9K views
Vapor – Swift is not only for iOS anymore by Milan Vít
Vapor – Swift is not only for iOS anymoreVapor – Swift is not only for iOS anymore
Vapor – Swift is not only for iOS anymore
Milan Vít224 views
Terraform GitOps on Codefresh by Codefresh
Terraform GitOps on CodefreshTerraform GitOps on Codefresh
Terraform GitOps on Codefresh
Codefresh2.5K views
From Zero to Application Delivery with NixOS by Susan Potter
From Zero to Application Delivery with NixOSFrom Zero to Application Delivery with NixOS
From Zero to Application Delivery with NixOS
Susan Potter2.9K views
Refactor case study LAN example by Tom Mens
Refactor case study LAN exampleRefactor case study LAN example
Refactor case study LAN example
Tom Mens729 views

Recently uploaded

DSD-INT 2023 The Danube Hazardous Substances Model - Kovacs by
DSD-INT 2023 The Danube Hazardous Substances Model - KovacsDSD-INT 2023 The Danube Hazardous Substances Model - Kovacs
DSD-INT 2023 The Danube Hazardous Substances Model - KovacsDeltares
8 views17 slides
SAP FOR CONTRACT MANUFACTURING.pdf by
SAP FOR CONTRACT MANUFACTURING.pdfSAP FOR CONTRACT MANUFACTURING.pdf
SAP FOR CONTRACT MANUFACTURING.pdfVirendra Rai, PMP
11 views2 slides
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx by
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptxanimuscrm
13 views19 slides
Copilot Prompting Toolkit_All Resources.pdf by
Copilot Prompting Toolkit_All Resources.pdfCopilot Prompting Toolkit_All Resources.pdf
Copilot Prompting Toolkit_All Resources.pdfRiccardo Zamana
8 views4 slides
Keep by
KeepKeep
KeepGeniusee
75 views10 slides
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ... by
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...Donato Onofri
773 views34 slides

Recently uploaded(20)

DSD-INT 2023 The Danube Hazardous Substances Model - Kovacs by Deltares
DSD-INT 2023 The Danube Hazardous Substances Model - KovacsDSD-INT 2023 The Danube Hazardous Substances Model - Kovacs
DSD-INT 2023 The Danube Hazardous Substances Model - Kovacs
Deltares8 views
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx by animuscrm
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx
2023-November-Schneider Electric-Meetup-BCN Admin Group.pptx
animuscrm13 views
Copilot Prompting Toolkit_All Resources.pdf by Riccardo Zamana
Copilot Prompting Toolkit_All Resources.pdfCopilot Prompting Toolkit_All Resources.pdf
Copilot Prompting Toolkit_All Resources.pdf
Riccardo Zamana8 views
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ... by Donato Onofri
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...
Unmasking the Dark Art of Vectored Exception Handling: Bypassing XDR and EDR ...
Donato Onofri773 views
Headless JS UG Presentation.pptx by Jack Spektor
Headless JS UG Presentation.pptxHeadless JS UG Presentation.pptx
Headless JS UG Presentation.pptx
Jack Spektor7 views
SUGCON ANZ Presentation V2.1 Final.pptx by Jack Spektor
SUGCON ANZ Presentation V2.1 Final.pptxSUGCON ANZ Presentation V2.1 Final.pptx
SUGCON ANZ Presentation V2.1 Final.pptx
Jack Spektor22 views
DSD-INT 2023 Wave-Current Interaction at Montrose Tidal Inlet System and Its ... by Deltares
DSD-INT 2023 Wave-Current Interaction at Montrose Tidal Inlet System and Its ...DSD-INT 2023 Wave-Current Interaction at Montrose Tidal Inlet System and Its ...
DSD-INT 2023 Wave-Current Interaction at Montrose Tidal Inlet System and Its ...
Deltares10 views
DSD-INT 2023 Machine learning in hydraulic engineering - Exploring unseen fut... by Deltares
DSD-INT 2023 Machine learning in hydraulic engineering - Exploring unseen fut...DSD-INT 2023 Machine learning in hydraulic engineering - Exploring unseen fut...
DSD-INT 2023 Machine learning in hydraulic engineering - Exploring unseen fut...
Deltares6 views
A first look at MariaDB 11.x features and ideas on how to use them by Federico Razzoli
A first look at MariaDB 11.x features and ideas on how to use themA first look at MariaDB 11.x features and ideas on how to use them
A first look at MariaDB 11.x features and ideas on how to use them
Federico Razzoli45 views
MariaDB stored procedures and why they should be improved by Federico Razzoli
MariaDB stored procedures and why they should be improvedMariaDB stored procedures and why they should be improved
MariaDB stored procedures and why they should be improved
DSD-INT 2023 Delft3D FM Suite 2024.01 1D2D - Beta testing programme - Geertsema by Deltares
DSD-INT 2023 Delft3D FM Suite 2024.01 1D2D - Beta testing programme - GeertsemaDSD-INT 2023 Delft3D FM Suite 2024.01 1D2D - Beta testing programme - Geertsema
DSD-INT 2023 Delft3D FM Suite 2024.01 1D2D - Beta testing programme - Geertsema
Deltares17 views
DSD-INT 2023 Modelling litter in the Yarra and Maribyrnong Rivers (Australia)... by Deltares
DSD-INT 2023 Modelling litter in the Yarra and Maribyrnong Rivers (Australia)...DSD-INT 2023 Modelling litter in the Yarra and Maribyrnong Rivers (Australia)...
DSD-INT 2023 Modelling litter in the Yarra and Maribyrnong Rivers (Australia)...
Deltares9 views
DSD-INT 2023 - Delft3D User Days - Welcome - Day 3 - Afternoon by Deltares
DSD-INT 2023 - Delft3D User Days - Welcome - Day 3 - AfternoonDSD-INT 2023 - Delft3D User Days - Welcome - Day 3 - Afternoon
DSD-INT 2023 - Delft3D User Days - Welcome - Day 3 - Afternoon
Deltares15 views
DSD-INT 2023 Leveraging the results of a 3D hydrodynamic model to improve the... by Deltares
DSD-INT 2023 Leveraging the results of a 3D hydrodynamic model to improve the...DSD-INT 2023 Leveraging the results of a 3D hydrodynamic model to improve the...
DSD-INT 2023 Leveraging the results of a 3D hydrodynamic model to improve the...
Deltares6 views
.NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra... by Marc Müller
.NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra....NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra...
.NET Developer Conference 2023 - .NET Microservices mit Dapr – zu viel Abstra...
Marc Müller38 views
Generic or specific? Making sensible software design decisions by Bert Jan Schrijver
Generic or specific? Making sensible software design decisionsGeneric or specific? Making sensible software design decisions
Generic or specific? Making sensible software design decisions

The async/await concurrency pattern in Golang