SlideShare une entreprise Scribd logo
1  sur  31
Go Concurrency Basics
Goroutines, channels and standard library
By Vitalii Perehonchuk, Software Developer
www.eliftech.com
Go provides
Concurrent execution
Synchronization and messaging
Multi-way concurrent control
www.eliftech.com
Go does NOT provide
direct thread manipulation
Go multithreading is fully managed by Go runtime.
In Go you use goroutines in place of threads
www.eliftech.com
Go provides a race detector
Ran with “-race” flag. It watches for unsynchronized access to shared variables.
www.eliftech.com
Goroutine
▪ A lightweight “thread” of execution managed by Go runtime.
▪ A function ran independently in the same address space as other goroutines.
▪ It’s routine to create thousands of goroutines.
▪ Go web servers usually process each request
in a separate goroutine.
www.eliftech.com
Goroutine
func sidekick() {
// Will be never executed.
fmt.Println("Sidekick arrived")
}
func main() {
go sidekick()
fmt.Println("Hero arrived")
}
www.eliftech.com
Goroutine
func sidekick() {
// Will be executed this time.
fmt.Println("Sidekick arrived")
}
func main() {
go sidekick()
runtime.Gosched()
fmt.Println("Hero arrived")
}
www.eliftech.com
Goroutine anti-pattern
Do not create functions whose only purpose is to run a goroutine.
www.eliftech.com
Channel
Imagine it as a pipe
<-
<-
for communication of goroutines
www.eliftech.com
Channel
Imagine it as a pipe
for communication of goroutines
www.eliftech.com
Channel
A goroutine can wait for a value from a channel
www.eliftech.com
Channel
A goroutine can wait for a value from a channel
func main() {
myChan := make(chan int)
<- myChan
// deadlock
fmt.Println("Hi everyone")
}
www.eliftech.com
Channel
A goroutine can wait to send a value to a channel
func main() {
myChan := make(chan int)
myChan <- 1
// deadlock
fmt.Println("Hi everyone")
}
www.eliftech.com
Channel
A goroutine can close a channel
func sidekick(mChan chan<- string)
{
mChan <- "I have not so
much to say"
mChan <- "Sorry"
close(mChan)
}
func main() {
wfm := true
var m string
mChan := make(chan string)
go sidekick(mChan)
for {
m, wfm = <-mChan
if !wfm { break }
fmt.Printf("Message from
the sidekick: %sn", m)
}
fmt.Println("Thanks for
your attention.")
}
www.eliftech.com
Channel
A deadlock can occur when sending into channel
func sidekick(taskChannel <-chan
string) {
task := <- taskChannel
fmt.Printf(“Done: %sn”,
task)
fmt.Println(“Enough work
for today”)
}
func main() {
taskChannel := make(chan string)
go sidekick(taskChannel)
taskChannel <- “Wash the
dishes”
// deadlock
taskChannel <- “Do
laundry”
}
www.eliftech.com
Channel
A channel can have a buffer
func sidekick(taskChannel <-chan
string) {
task := <- taskChannel
fmt.Printf(“Done: %sn”,
task)
fmt.Println(“Enough work
for today”)
}
func main() {
taskChannel := make(chan string, 1)
go sidekick(taskChannel)
taskChannel <- “Wash the
dishes”
taskChannel <- “Do
laundry”
}
www.eliftech.com
Channel
“select” waits for a value from a set of channels
func sidekick() {
task := <-taskChan
time.Sleep(2 * time.Second)
resChan <- fmt.Sprintf(
"Done: %sn", task,
)
}
func main() {
// channels initialization
omitted
go sidekick(taskChan, resChan)
taskChan <- "Wash the dishes"
timer := time.NewTimer(1 *
time.Second)
var res string
select {
...
www.eliftech.com
Channel
“select” waits for a value from a set of channels
func sidekick() {
task := <-taskChan
time.Sleep(2 * time.Second)
resChan <- fmt.Sprintf(
"Done: %sn", task,
)
}
...
select {
case res = <- resChan:
fmt.Println(res)
case <- timer.C:
fmt.Println("SIDEKICK!")
fmt.Println("What are you
doing?")
}
}
www.eliftech.com
Channel anti-pattern
Do not guard channels with mutexes.
Channels don’t need concurrency control.
They are concurrency control.
www.eliftech.com
Utilities
runtime, sync
www.eliftech.com
type sync.Mutex
▪ Mutual exclusion lock.
▪ Zero value is unlocked
www.eliftech.com
type sync.WaitGroup
Makes a goroutine block until some work is done
www.eliftech.com
type sync.Mutex, type sync.WaitGroup
var c = 0
var cMutex sync.Mutex
var waitGroup sync.WaitGroup
func sidekick() {
cMutex.Lock()
c ++
cMutex.Unlock()
waitGroup.Done()
}
func main() {
waitGroup.Add(n)
for i := 0; i < n; i++ {
go sidekick()
}
waitGroup.Wait()
cMutex.Lock()
fmt.Printf("Counter's value:
%dn", c)
cMutex.Unlock()
}
www.eliftech.com
type sync.RWMutex
Reader / writer mutual exclusion
lock. Many readers, single writer
simultaneously
type sync.Once
Performs only one action only once
www.eliftech.com
type sync.Pool type sync.Map type sync.Cond
Thread-safe collection
of temporary objects
Map safe for
concurrent use
Condition object used
to announce an event
www.eliftech.com
runtime.GOMAXPROCS(int) int
▪ Function to set maximum number of native threads run simultaneously.
▪ Defaults to number of CPUs (since Go 1.6, previously defaulted to 1)
www.eliftech.com
runtime.NumGoroutine() int
Returns the number of goroutines that currently exist.
www.eliftech.com
runtime.Gosched()
Explicitly make Go scheduler switch contexts - let other goroutines run
www.eliftech.com
Conclusion
Go concurrency is cheap
Go concurrency is complicated (as any concurrency)
Go concurrency is powerful
www.eliftech.com
Sources
▪ “Mastering concurrency in Go” by Nathan Kozyra
▪ Golang.org
▪ “Learning Go’s concurrency through illustrations” by Trevor Forrey
▪ “Go Antipatterns” at hackmongo.com
www.eliftech.com
Don't forget to subscribe not to
miss our next presentations!
Find us at eliftech.com
Have a question? Contact us:
info@eliftech.com

Contenu connexe

Tendances

The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
jeffz
 

Tendances (20)

scala-gopher: async implementation of CSP for scala
scala-gopher:  async implementation of CSP  for  scalascala-gopher:  async implementation of CSP  for  scala
scala-gopher: async implementation of CSP for scala
 
Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.
 
OTcl and C++ linkages in NS2
OTcl and C++ linkages in NS2OTcl and C++ linkages in NS2
OTcl and C++ linkages in NS2
 
Using zone.js
Using zone.jsUsing zone.js
Using zone.js
 
A deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio moduleA deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio module
 
Rcpp11
Rcpp11Rcpp11
Rcpp11
 
R/C++ talk at earl 2014
R/C++ talk at earl 2014R/C++ talk at earl 2014
R/C++ talk at earl 2014
 
Python Coroutines, Present and Future
Python Coroutines, Present and FuturePython Coroutines, Present and Future
Python Coroutines, Present and Future
 
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
 
Java agents are watching your ByteCode
Java agents are watching your ByteCodeJava agents are watching your ByteCode
Java agents are watching your ByteCode
 
Concurrency with Go
Concurrency with GoConcurrency with Go
Concurrency with Go
 
FSE 2008
FSE 2008FSE 2008
FSE 2008
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015
 
Coroutines talk ppt
Coroutines talk pptCoroutines talk ppt
Coroutines talk ppt
 
Demystifying the Go Scheduler
Demystifying the Go SchedulerDemystifying the Go Scheduler
Demystifying the Go Scheduler
 
Java/Scala Lab: Руслан Шевченко - Implementation of CSP (Communication Sequen...
Java/Scala Lab: Руслан Шевченко - Implementation of CSP (Communication Sequen...Java/Scala Lab: Руслан Шевченко - Implementation of CSP (Communication Sequen...
Java/Scala Lab: Руслан Шевченко - Implementation of CSP (Communication Sequen...
 
ClojureScript for the web
ClojureScript for the webClojureScript for the web
ClojureScript for the web
 
Functional Reactive Programming in Clojurescript
Functional Reactive Programming in ClojurescriptFunctional Reactive Programming in Clojurescript
Functional Reactive Programming in Clojurescript
 
Full Stack Clojure
Full Stack ClojureFull Stack Clojure
Full Stack Clojure
 
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)The Evolution of Async-Programming on .NET Platform (.Net China, C#)
The Evolution of Async-Programming on .NET Platform (.Net China, C#)
 

Similaire à Go Concurrency Basics

An Introduction to Go
An Introduction to GoAn Introduction to Go
An Introduction to Go
Cloudflare
 
Go Concurrency
Go ConcurrencyGo Concurrency
Go Concurrency
Cloudflare
 

Similaire à Go Concurrency Basics (20)

Go lang introduction
Go lang introductionGo lang introduction
Go lang introduction
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in Golang
 
10 reasons to be excited about go
10 reasons to be excited about go10 reasons to be excited about go
10 reasons to be excited about go
 
LCA2014 - Introduction to Go
LCA2014 - Introduction to GoLCA2014 - Introduction to Go
LCA2014 - Introduction to Go
 
Deep Dive async/await in Unity with UniTask(EN)
Deep Dive async/await in Unity with UniTask(EN)Deep Dive async/await in Unity with UniTask(EN)
Deep Dive async/await in Unity with UniTask(EN)
 
An Introduction to Go
An Introduction to GoAn Introduction to Go
An Introduction to Go
 
Async fun
Async funAsync fun
Async fun
 
golang_getting_started.pptx
golang_getting_started.pptxgolang_getting_started.pptx
golang_getting_started.pptx
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
 
Writing Docker monitoring agent with Go
Writing Docker monitoring agent with GoWriting Docker monitoring agent with Go
Writing Docker monitoring agent with Go
 
Writing Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & AkkaWriting Asynchronous Programs with Scala & Akka
Writing Asynchronous Programs with Scala & Akka
 
Go Concurrency
Go ConcurrencyGo Concurrency
Go Concurrency
 
Communication in Python and the C10k problem
Communication in Python and the C10k problemCommunication in Python and the C10k problem
Communication in Python and the C10k problem
 
Go Lang Tutorial
Go Lang TutorialGo Lang Tutorial
Go Lang Tutorial
 
Fundamental concurrent programming
Fundamental concurrent programmingFundamental concurrent programming
Fundamental concurrent programming
 
Csp scala wixmeetup2016
Csp scala wixmeetup2016Csp scala wixmeetup2016
Csp scala wixmeetup2016
 
Go on!
Go on!Go on!
Go on!
 
Intro to GO (Bangkok Launchpad 2014)
Intro to GO (Bangkok Launchpad 2014)Intro to GO (Bangkok Launchpad 2014)
Intro to GO (Bangkok Launchpad 2014)
 
JVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in KotlinJVMLS 2016. Coroutines in Kotlin
JVMLS 2016. Coroutines in Kotlin
 
Appsec obfuscator reloaded
Appsec obfuscator reloadedAppsec obfuscator reloaded
Appsec obfuscator reloaded
 

Plus de ElifTech

Plus de ElifTech (20)

Domain Logic Patterns
Domain Logic PatternsDomain Logic Patterns
Domain Logic Patterns
 
Dive into .Net Core framework
Dive into .Net Core framework Dive into .Net Core framework
Dive into .Net Core framework
 
VR digest. August 2018
VR digest. August 2018VR digest. August 2018
VR digest. August 2018
 
JS digest. July 2018
JS digest.  July 2018JS digest.  July 2018
JS digest. July 2018
 
VR digest. July 2018
VR digest. July 2018VR digest. July 2018
VR digest. July 2018
 
IoT digest. July 2018
IoT digest. July 2018IoT digest. July 2018
IoT digest. July 2018
 
VR digest. June 2018
VR digest. June 2018VR digest. June 2018
VR digest. June 2018
 
IoT digest. June 2018
IoT digest. June 2018IoT digest. June 2018
IoT digest. June 2018
 
IoT digest. May 2018
IoT digest. May 2018IoT digest. May 2018
IoT digest. May 2018
 
Object Detection with Tensorflow
Object Detection with TensorflowObject Detection with Tensorflow
Object Detection with Tensorflow
 
VR digest. May 2018
VR digest. May 2018VR digest. May 2018
VR digest. May 2018
 
Polymer: brief introduction
Polymer: brief introduction Polymer: brief introduction
Polymer: brief introduction
 
JS digest. April 2018
JS digest. April 2018JS digest. April 2018
JS digest. April 2018
 
VR digest. April, 2018
VR digest. April, 2018 VR digest. April, 2018
VR digest. April, 2018
 
IoT digest. April 2018
IoT digest. April 2018IoT digest. April 2018
IoT digest. April 2018
 
IoT digest. March 2018
IoT digest. March 2018IoT digest. March 2018
IoT digest. March 2018
 
VR digest. March, 2018
VR digest. March, 2018VR digest. March, 2018
VR digest. March, 2018
 
VR digest. February, 2018
VR digest. February, 2018VR digest. February, 2018
VR digest. February, 2018
 
IoT digest. February 2018
IoT digest. February 2018IoT digest. February 2018
IoT digest. February 2018
 
JS digest. January 2018
JS digest. January 2018 JS digest. January 2018
JS digest. January 2018
 

Dernier

AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 

Dernier (20)

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 

Go Concurrency Basics