SlideShare a Scribd company logo
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

More Related Content

PPTX
Go Concurrency Patterns
PDF
Go Concurrency
PDF
Golang Channels
PDF
Goroutines and Channels in practice
PDF
Go concurrency
PDF
Concurrency in Golang
PPT
Concurrency in go
PDF
Coroutines in Kotlin
Go Concurrency Patterns
Go Concurrency
Golang Channels
Goroutines and Channels in practice
Go concurrency
Concurrency in Golang
Concurrency in go
Coroutines in Kotlin

What's hot (20)

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

Similar to Go Concurrency Basics (20)

PPT
Go lang introduction
PDF
Job Queue in Golang
PDF
10 reasons to be excited about go
PDF
LCA2014 - Introduction to Go
PDF
Deep Dive async/await in Unity with UniTask(EN)
PDF
An Introduction to Go
PPTX
PPTX
golang_getting_started.pptx
PPTX
Async programming and python
PDF
Writing Docker monitoring agent with Go
PDF
Writing Asynchronous Programs with Scala & Akka
PDF
Go Concurrency
PDF
Communication in Python and the C10k problem
PDF
Go Lang Tutorial
PPTX
Fundamental concurrent programming
PDF
Csp scala wixmeetup2016
PDF
Go on!
PDF
Intro to GO (Bangkok Launchpad 2014)
PDF
JVMLS 2016. Coroutines in Kotlin
PDF
Appsec obfuscator reloaded
Go lang introduction
Job Queue in Golang
10 reasons to be excited about go
LCA2014 - Introduction to Go
Deep Dive async/await in Unity with UniTask(EN)
An Introduction to Go
golang_getting_started.pptx
Async programming and python
Writing Docker monitoring agent with Go
Writing Asynchronous Programs with Scala & Akka
Go Concurrency
Communication in Python and the C10k problem
Go Lang Tutorial
Fundamental concurrent programming
Csp scala wixmeetup2016
Go on!
Intro to GO (Bangkok Launchpad 2014)
JVMLS 2016. Coroutines in Kotlin
Appsec obfuscator reloaded
Ad

More from ElifTech (20)

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

Recently uploaded (20)

PPTX
Odoo POS Development Services by CandidRoot Solutions
PPTX
assetexplorer- product-overview - presentation
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
Digital Strategies for Manufacturing Companies
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PDF
top salesforce developer skills in 2025.pdf
PDF
Digital Systems & Binary Numbers (comprehensive )
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
Softaken Excel to vCard Converter Software.pdf
PPTX
Transform Your Business with a Software ERP System
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PPTX
Log360_SIEM_Solutions Overview PPT_Feb 2020.pptx
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PPTX
CHAPTER 2 - PM Management and IT Context
Odoo POS Development Services by CandidRoot Solutions
assetexplorer- product-overview - presentation
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Digital Strategies for Manufacturing Companies
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
top salesforce developer skills in 2025.pdf
Digital Systems & Binary Numbers (comprehensive )
Navsoft: AI-Powered Business Solutions & Custom Software Development
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Softaken Excel to vCard Converter Software.pdf
Transform Your Business with a Software ERP System
How to Choose the Right IT Partner for Your Business in Malaysia
Odoo Companies in India – Driving Business Transformation.pdf
Design an Analysis of Algorithms I-SECS-1021-03
Log360_SIEM_Solutions Overview PPT_Feb 2020.pptx
Design an Analysis of Algorithms II-SECS-1021-03
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Adobe Illustrator 28.6 Crack My Vision of Vector Design
CHAPTER 2 - PM Management and IT Context

Go Concurrency Basics