SlideShare a Scribd company logo
Concurrency under the hood
by Denys Goldiner
Concurrency under the hood
by Denys Goldiner
Practical concurrency
by Denys Goldiner
Practical concurrency
and some theory behind it
by Denys Goldiner
What is concurrency?
- asynchrony
- goroutines
- synchronization
- shared memory
- message communication
- execution planning
- scheduler
Questions I had in practice
- is sync.Mutex absolutely safe?
- how much does shared memory cost?
- what is the secret of a nil channel?
- is channel absolutely safe?
- how to plan execution?
- how to rule the concurrency?
- how many goroutines do you need?
Is sync.Mutex absolutely safe?
Data race with mutex
func main() {
var wg sync.WaitGroup
ctx, cancel := context.WithCancel(context.Background())
wg.Add(2)
go checkCtxErr(&wg, ctx)
go checkCtxVal(&wg, ctx)
time.Sleep(1 * time.Second)
cancel()
wg.Wait()
}
Data race with mutex
func checkCtxErr(wg *sync.WaitGroup, ctx context.Context) {
defer wg.Done()
for {
select {
case <-ctx.Done():
return
default:
if err := ctx.Err(); err != nil {
return
}
}
}
}
Data race with mutex
func checkCtxVal(wg *sync.WaitGroup, ctx context.Context) {
defer wg.Done()
expectedCtx, _ := context.WithCancel(context.Background())
for {
select {
case <-ctx.Done():
return
default:
if reflect.DeepEqual(expectedCtx, ctx) {
return
}
}
}
}
Data race with mutex
WARNING: DATA RACE
- Read by goroutine 7:
- reflect.deepValueEqual()
- reflect.DeepEqual()
- main.checkCtxVal()
- Previous write by goroutine 6:
- sync/atomic.CompareAndSwapInt32()
- sync.(*Mutex).Lock()
- context.(*cancelCtx).Done()
- main.checkCtxErr()
Data race with mutex
type cancelCtx struct {
Context
mu sync.Mutex
done chan struct{}
children map[canceler]struct{}
err error
}
func (c *cancelCtx) Err() error {
c.mu.Lock()
err := c.err
c.mu.Unlock()
return err
}
Be careful with reflect!
How much does shared memory cost?
False sharing, cache invalidation (core i7-9xxx)
L3 cache
L2 cache
L2 cache Main
Memory
core1core2core3core4
L1 I-cache
L1 D-cache
T0
T1
L1 I-cache
L1 D-cache
T0
T1
L2 cache
L1 I-cache
L1 D-cache
T0
T1
L2 cache
L1 I-cache
L1 D-cache
T0
T1
False sharing, cache invalidation
func main() {
arr := make([]int, 1000)
wg := sync.WaitGroup{}
wg.Add(len(arr))
for i := 0; i < len(arr); i++ {
go func(wg *sync.WaitGroup, i int) {
arr[i] = i * i
wg.Done()
}(&wg, i)
}
wg.Wait()
}
Map + sync.RWMutex
type safeMap struct {
data map[int]struct{}
sync.RWMutex
}
func (sm *safeMap) check(v int) bool {
sm.RLock()
_, ok := sm.data[v]
sm.RUnlock()
return ok
}
Map + sync.RWMutex
func mapUse(n int) {
var sm = &safeMap{data: map[int]struct{}{0: {}, 1: {}, 2: {}}}
var wg sync.WaitGroup
wg.Add(n)
for i := 0; i < n; i++ {
go func(wg *sync.WaitGroup) {
_ = sm.check(i % 3)
wg.Done()
}(&wg)
}
wg.Wait()
}
Map + mutex vs sync.Map
cores
iterations
map + sync.RWMutex
sync.Map
Sync.Map use cases
- stable keys
- once written, many times read
- many threads
How to avoid false sharing?
Use message communication
Using message communication
func communication(arr []int) {
ch := make(chan update)
for i := 0; i < len(arr); i++ {
go func(ch chan update, i int) {
ch <- update{id: i, val: i * i}
}(ch, i)
}
for j := 0; j < len(arr); j++ {
iu := <-ch
arr[iu.id] = iu.val
}
}
What is the secret of a nil channel?
Nil channel
func main() {
ch1 := make(chan struct{})
ch2 := make(chan struct{})
var wg sync.WaitGroup
wg.Add(1)
go fanIn(&wg, ch1, ch2)
close(ch1)
time.Sleep(1 * time.Second)
close(ch2)
wg.Wait()
}
Nil channel
func fanIn(wg *sync.WaitGroup, ch1, ch2 <-chan struct{}) {
defer wg.Done()
var b1, b2 bool
for !b1 || !b2 {
select {
case _, ok := <-ch1:
if !ok { b1 = true }
fmt.Println("case 1")
case _, ok := <-ch2:
if !ok { b2 = true }
fmt.Println("case 2")
}
}
}
Nil channel
- case 1
- case 1
- case 1
- case 1
- ...
- case 1
- case 1
- case 1
- case 1
- case 2
- Process finished with exit code 0
Nil channel
func fanInUpgrade(wg *sync.WaitGroup, ch1, ch2 <-chan struct{}) {
defer wg.Done()
for ch1 != nil || ch2 != nil {
select {
case _, ok := <-ch1:
if !ok { ch1 = nil }
fmt.Println("case 1")
case _, ok := <-ch2:
if !ok { ch2 = nil }
fmt.Println("case 2")
}
}
}
Nil channel
- case 1
- case 2
- Process finished with exit code 0
Is channel absolutely safe?
Data race with channel
func main() {
ch := make(chan struct{})
go func() {
<-ch
}()
ch = nil
}
// data race
Data race with channel
func main() {
ch := make(chan struct{})
go func(ch chan struct{}) {
<-ch
}(ch)
ch = nil
}
// no data race
Data race with channel
func main() {
ch := make(chan struct{})
go func(ch *chan struct{}) {
<-*ch
}(&ch)
ch = nil
}
// data race
Channels
type hchan struct {
qcount uint // total data in the queue
dataqsiz uint // size of the circular queue
buf unsafe.Pointer // points to an array of dataqsiz elements
elemsize uint16
closed uint32
elemtype *_type // element type
sendx uint // send index
recvx uint // receive index
recvq waitq // list of recv waiters
sendq waitq // list of send waiters
lock mutex
}
Data race with channel
func makechan(t *chantype, size int) *hchan {
…
}
func makemap(t *maptype, hint int, h *hmap) *hmap {
…
}
func makeslice(et *_type, len, cap int) unsafe.Pointer {
…
}
Data race with channel
func main() {
ch := make(chan struct{})
go func(ch chan struct{}) {
ch = nil
}(ch)
log.Println(ch == nil) // false
}
func main() {
ch := make(chan struct{})
go func(ch chan struct{}) {
log.Println(ch == nil) // false
}(ch)
ch = nil
}
Take it in mind using nil in select
Data race with data from channel
func dataRace() {
ch := make(chan *int)
go func() {
b := <-ch
*b++
}()
var a = 5
ch <- &a
a++
}
Pay attention to pointers
How to plan execution?
Scheduler (execution planning)
- processor threads
- OS threads
- scheduler
- context switch
- software threads
What is an execution context?
It’s a number of registers needed to restore the thread
execution:
- Program Counter (PC)
- Stack Pointer (SP)
- …
What is an execution context?
- context switch is not for free!
- we need a predictable execution context switch
Statement of a problem
- CPU-bound (working) - MAXIMIZE
- workload for all available threads - MAXIMIZE
- IO-bound (waiting) - MINIMIZE
- execution context switching - MINIMIZE
We need our own scheduler
Goroutine execution
M1
G1
P1
G2 G3 G4
Core
LRQ
System calls planning
M2
G2
P1
G3 G4
Core
LRQ
M1
G1
System calls planning
M2
G2
P1
G3 G4
Core
LRQ
M1
G1
Parallelism
M2
G4
P2
G5 G6
LRQ
M1
G1
P1
G2 G3
LRQ
GRQ
G7
Work steal
M2
G4
P2
G5 G6
LRQ
M1
P1
LRQ
GRQ
G7
- 1/61 off the time, check global queue
- check local queue
- try to steal half of work from other P
- check the global queue
- poll network
Work steal & GRQ
Work steal
M2
G4
P2
G5 G6
LRQ
M1
P1
LRQ
GRQ
G7
Work steal
M1
G6
P1
LRQ
GRQ
G7
M2
G4
P2
G5
LRQ
Work steal
M2
G5
P2
LRQ
M1
P1
LRQ
GRQ
G7
Work steal
M2
G5
P2
LRQ
M1
G7
P1
LRQ
GRQ
How to rule the concurrency?
Channels and FIFO
- FIFO read goroutine queue
- FIFO write goroutine queue
- FIFO buffer
Channels and FIFO
- FIFO read goroutine queue
- FIFO write goroutine queue
- FIFO buffer
Context switch conditions
- GC
- system calls (blocking / non-blocking / Cgo)
- function calls
- goroutine creation
- synchronization operations
- special function runtime.Gosched()
It means other goroutines might start execution
GOMAXPROCS
- sets P number
- for go run
- for tests (go test -cpu <number>)
How many goroutines do you need?
How many goroutines do you need?
- small amount of goroutines is bad
- huge amount of goroutines is bad
How many goroutines do you need?
- type of work (IO / CPU bound)
- how many blocking operations do you have
- how many threads do you have
- how much garbage does your program produce
The amount of goroutines is an empirical
value
Bonus: 7 steps to effective concurrency
- finish synchronous version of the program
- write benchmarks to measure results
- optimize synchronous implementation
- check if your solution fits for concurrency
- make your code concurrent
- measure results
- optimize concurrent implementation
Links
- https://habr.com/ru/post/338718/
- https://www.ardanlabs.com/blog/2018/08/scheduling-in-go-part1.html
- https://medium.com/@riteeksrivastava/a-complete-journey-with-goroutines-8472630c7f5c
- https://www.youtube.com/watch?v=t9bEg2A4jsw

More Related Content

What's hot

FOSDEM 2020: Querying over millions and billions of metrics with M3DB's index
FOSDEM 2020: Querying over millions and billions of metrics with M3DB's indexFOSDEM 2020: Querying over millions and billions of metrics with M3DB's index
FOSDEM 2020: Querying over millions and billions of metrics with M3DB's index
Rob Skillington
 
Scheduling in Linux and Web Servers
Scheduling in Linux and Web ServersScheduling in Linux and Web Servers
Scheduling in Linux and Web Servers
David Evans
 
SSL Failing, Sharing, and Scheduling
SSL Failing, Sharing, and SchedulingSSL Failing, Sharing, and Scheduling
SSL Failing, Sharing, and Scheduling
David Evans
 
Synchronization
SynchronizationSynchronization
Synchronization
David Evans
 
Errors errors, everywhere! - JSession
Errors errors, everywhere! - JSessionErrors errors, everywhere! - JSession
Errors errors, everywhere! - JSession
Daniel Pokusa
 
計算機性能の限界点とその考え方
計算機性能の限界点とその考え方計算機性能の限界点とその考え方
計算機性能の限界点とその考え方
Naoto MATSUMOTO
 
Deep dumpster diving 2010
Deep dumpster diving 2010Deep dumpster diving 2010
Deep dumpster diving 2010
RonnBlack
 
CS6401 Operating systems - Solved Examples
CS6401 Operating systems - Solved ExamplesCS6401 Operating systems - Solved Examples
CS6401 Operating systems - Solved Examples
ramyaranjith
 
Transaction Timestamping in Temporal Databases
Transaction Timestamping in Temporal DatabasesTransaction Timestamping in Temporal Databases
Transaction Timestamping in Temporal Databases
Gera Shegalov
 
doc
docdoc
Implementation of Bitcoin Miner on SW and HW
Implementation of Bitcoin Miner on SW and HWImplementation of Bitcoin Miner on SW and HW
Implementation of Bitcoin Miner on SW and HW
Joe Jiang
 
Next Generation Indexes For Big Data Engineering (ODSC East 2018)
Next Generation Indexes For Big Data Engineering (ODSC East 2018)Next Generation Indexes For Big Data Engineering (ODSC East 2018)
Next Generation Indexes For Big Data Engineering (ODSC East 2018)
Daniel Lemire
 
Network simulator 2
Network simulator 2Network simulator 2
Network simulator 2
Pradeep Kumar TS
 
Processes And Job Control
Processes And Job ControlProcesses And Job Control
Processes And Job Control
ahmad bassiouny
 
Hathor@FGV: Introductory notes by Dr. A. Linhares
Hathor@FGV: Introductory notes by Dr. A. LinharesHathor@FGV: Introductory notes by Dr. A. Linhares
Hathor@FGV: Introductory notes by Dr. A. Linhares
Alexandre Linhares
 
Porting and optimizing UniFrac for GPUs
Porting and optimizing UniFrac for GPUsPorting and optimizing UniFrac for GPUs
Porting and optimizing UniFrac for GPUs
Igor Sfiligoi
 
[Globant summer take over] Empowering Big Data with Cassandra
[Globant summer take over] Empowering Big Data with Cassandra[Globant summer take over] Empowering Big Data with Cassandra
[Globant summer take over] Empowering Big Data with Cassandra
Globant
 
Introduction to RevKit
Introduction to RevKitIntroduction to RevKit
Introduction to RevKit
Mathias Soeken
 
Fast indexes with roaring #gomtl-10
Fast indexes with roaring #gomtl-10 Fast indexes with roaring #gomtl-10
Fast indexes with roaring #gomtl-10
Daniel Lemire
 
Sujet bac info 2013 g1, g2 et g3 avec correction
Sujet bac info 2013 g1, g2 et g3 avec correctionSujet bac info 2013 g1, g2 et g3 avec correction
Sujet bac info 2013 g1, g2 et g3 avec correction
borhen boukthir
 

What's hot (20)

FOSDEM 2020: Querying over millions and billions of metrics with M3DB's index
FOSDEM 2020: Querying over millions and billions of metrics with M3DB's indexFOSDEM 2020: Querying over millions and billions of metrics with M3DB's index
FOSDEM 2020: Querying over millions and billions of metrics with M3DB's index
 
Scheduling in Linux and Web Servers
Scheduling in Linux and Web ServersScheduling in Linux and Web Servers
Scheduling in Linux and Web Servers
 
SSL Failing, Sharing, and Scheduling
SSL Failing, Sharing, and SchedulingSSL Failing, Sharing, and Scheduling
SSL Failing, Sharing, and Scheduling
 
Synchronization
SynchronizationSynchronization
Synchronization
 
Errors errors, everywhere! - JSession
Errors errors, everywhere! - JSessionErrors errors, everywhere! - JSession
Errors errors, everywhere! - JSession
 
計算機性能の限界点とその考え方
計算機性能の限界点とその考え方計算機性能の限界点とその考え方
計算機性能の限界点とその考え方
 
Deep dumpster diving 2010
Deep dumpster diving 2010Deep dumpster diving 2010
Deep dumpster diving 2010
 
CS6401 Operating systems - Solved Examples
CS6401 Operating systems - Solved ExamplesCS6401 Operating systems - Solved Examples
CS6401 Operating systems - Solved Examples
 
Transaction Timestamping in Temporal Databases
Transaction Timestamping in Temporal DatabasesTransaction Timestamping in Temporal Databases
Transaction Timestamping in Temporal Databases
 
doc
docdoc
doc
 
Implementation of Bitcoin Miner on SW and HW
Implementation of Bitcoin Miner on SW and HWImplementation of Bitcoin Miner on SW and HW
Implementation of Bitcoin Miner on SW and HW
 
Next Generation Indexes For Big Data Engineering (ODSC East 2018)
Next Generation Indexes For Big Data Engineering (ODSC East 2018)Next Generation Indexes For Big Data Engineering (ODSC East 2018)
Next Generation Indexes For Big Data Engineering (ODSC East 2018)
 
Network simulator 2
Network simulator 2Network simulator 2
Network simulator 2
 
Processes And Job Control
Processes And Job ControlProcesses And Job Control
Processes And Job Control
 
Hathor@FGV: Introductory notes by Dr. A. Linhares
Hathor@FGV: Introductory notes by Dr. A. LinharesHathor@FGV: Introductory notes by Dr. A. Linhares
Hathor@FGV: Introductory notes by Dr. A. Linhares
 
Porting and optimizing UniFrac for GPUs
Porting and optimizing UniFrac for GPUsPorting and optimizing UniFrac for GPUs
Porting and optimizing UniFrac for GPUs
 
[Globant summer take over] Empowering Big Data with Cassandra
[Globant summer take over] Empowering Big Data with Cassandra[Globant summer take over] Empowering Big Data with Cassandra
[Globant summer take over] Empowering Big Data with Cassandra
 
Introduction to RevKit
Introduction to RevKitIntroduction to RevKit
Introduction to RevKit
 
Fast indexes with roaring #gomtl-10
Fast indexes with roaring #gomtl-10 Fast indexes with roaring #gomtl-10
Fast indexes with roaring #gomtl-10
 
Sujet bac info 2013 g1, g2 et g3 avec correction
Sujet bac info 2013 g1, g2 et g3 avec correctionSujet bac info 2013 g1, g2 et g3 avec correction
Sujet bac info 2013 g1, g2 et g3 avec correction
 

Similar to Concurrency in Go by Denys Goldiner.pdf

Capturing NIC and Kernel TX and RX Timestamps for Packets in Go
Capturing NIC and Kernel TX and RX Timestamps for Packets in GoCapturing NIC and Kernel TX and RX Timestamps for Packets in Go
Capturing NIC and Kernel TX and RX Timestamps for Packets in Go
ScyllaDB
 
So you think you can stream.pptx
So you think you can stream.pptxSo you think you can stream.pptx
So you think you can stream.pptx
Prakash Chockalingam
 
What’s new in 9.6, by PostgreSQL contributor
What’s new in 9.6, by PostgreSQL contributorWhat’s new in 9.6, by PostgreSQL contributor
What’s new in 9.6, by PostgreSQL contributor
Masahiko Sawada
 
用 Go 語言打造多台機器 Scale 架構
用 Go 語言打造多台機器 Scale 架構用 Go 語言打造多台機器 Scale 架構
用 Go 語言打造多台機器 Scale 架構
Bo-Yi Wu
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in Golang
Bo-Yi Wu
 
Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++
Yandex
 
Writing a TSDB from scratch_ performance optimizations.pdf
Writing a TSDB from scratch_ performance optimizations.pdfWriting a TSDB from scratch_ performance optimizations.pdf
Writing a TSDB from scratch_ performance optimizations.pdf
RomanKhavronenko
 
Apache Flink: API, runtime, and project roadmap
Apache Flink: API, runtime, and project roadmapApache Flink: API, runtime, and project roadmap
Apache Flink: API, runtime, and project roadmap
Kostas Tzoumas
 
Router Queue Simulation in C++ in MMNN and MM1 conditions
Router Queue Simulation in C++ in MMNN and MM1 conditionsRouter Queue Simulation in C++ in MMNN and MM1 conditions
Router Queue Simulation in C++ in MMNN and MM1 conditions
Morteza Mahdilar
 
Go concurrency
Go concurrencyGo concurrency
Go concurrency
siuyin
 
The Effect of Hierarchical Memory on the Design of Parallel Algorithms and th...
The Effect of Hierarchical Memory on the Design of Parallel Algorithms and th...The Effect of Hierarchical Memory on the Design of Parallel Algorithms and th...
The Effect of Hierarchical Memory on the Design of Parallel Algorithms and th...
David Walker
 
Distributed Computing Patterns in R
Distributed Computing Patterns in RDistributed Computing Patterns in R
Distributed Computing Patterns in R
armstrtw
 
Rust "Hot or Not" at Sioux
Rust "Hot or Not" at SiouxRust "Hot or Not" at Sioux
Rust "Hot or Not" at Sioux
nikomatsakis
 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the way
Oleg Podsechin
 
Venkat ns2
Venkat ns2Venkat ns2
Venkat ns2
venkatnampally
 
Go and Uber’s time series database m3
Go and Uber’s time series database m3Go and Uber’s time series database m3
Go and Uber’s time series database m3
Rob Skillington
 
Skyline queries
Skyline queriesSkyline queries
Skyline queries
Victor Torras
 
Samantha Wang [InfluxData] | Best Practices on How to Transform Your Data Usi...
Samantha Wang [InfluxData] | Best Practices on How to Transform Your Data Usi...Samantha Wang [InfluxData] | Best Practices on How to Transform Your Data Usi...
Samantha Wang [InfluxData] | Best Practices on How to Transform Your Data Usi...
InfluxData
 
Continuous Application with Structured Streaming 2.0
Continuous Application with Structured Streaming 2.0Continuous Application with Structured Streaming 2.0
Continuous Application with Structured Streaming 2.0
Anyscale
 
Data Analytics and Simulation in Parallel with MATLAB*
Data Analytics and Simulation in Parallel with MATLAB*Data Analytics and Simulation in Parallel with MATLAB*
Data Analytics and Simulation in Parallel with MATLAB*
Intel® Software
 

Similar to Concurrency in Go by Denys Goldiner.pdf (20)

Capturing NIC and Kernel TX and RX Timestamps for Packets in Go
Capturing NIC and Kernel TX and RX Timestamps for Packets in GoCapturing NIC and Kernel TX and RX Timestamps for Packets in Go
Capturing NIC and Kernel TX and RX Timestamps for Packets in Go
 
So you think you can stream.pptx
So you think you can stream.pptxSo you think you can stream.pptx
So you think you can stream.pptx
 
What’s new in 9.6, by PostgreSQL contributor
What’s new in 9.6, by PostgreSQL contributorWhat’s new in 9.6, by PostgreSQL contributor
What’s new in 9.6, by PostgreSQL contributor
 
用 Go 語言打造多台機器 Scale 架構
用 Go 語言打造多台機器 Scale 架構用 Go 語言打造多台機器 Scale 架構
用 Go 語言打造多台機器 Scale 架構
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in Golang
 
Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++Степан Кольцов — Rust — лучше, чем C++
Степан Кольцов — Rust — лучше, чем C++
 
Writing a TSDB from scratch_ performance optimizations.pdf
Writing a TSDB from scratch_ performance optimizations.pdfWriting a TSDB from scratch_ performance optimizations.pdf
Writing a TSDB from scratch_ performance optimizations.pdf
 
Apache Flink: API, runtime, and project roadmap
Apache Flink: API, runtime, and project roadmapApache Flink: API, runtime, and project roadmap
Apache Flink: API, runtime, and project roadmap
 
Router Queue Simulation in C++ in MMNN and MM1 conditions
Router Queue Simulation in C++ in MMNN and MM1 conditionsRouter Queue Simulation in C++ in MMNN and MM1 conditions
Router Queue Simulation in C++ in MMNN and MM1 conditions
 
Go concurrency
Go concurrencyGo concurrency
Go concurrency
 
The Effect of Hierarchical Memory on the Design of Parallel Algorithms and th...
The Effect of Hierarchical Memory on the Design of Parallel Algorithms and th...The Effect of Hierarchical Memory on the Design of Parallel Algorithms and th...
The Effect of Hierarchical Memory on the Design of Parallel Algorithms and th...
 
Distributed Computing Patterns in R
Distributed Computing Patterns in RDistributed Computing Patterns in R
Distributed Computing Patterns in R
 
Rust "Hot or Not" at Sioux
Rust "Hot or Not" at SiouxRust "Hot or Not" at Sioux
Rust "Hot or Not" at Sioux
 
Server side JavaScript: going all the way
Server side JavaScript: going all the wayServer side JavaScript: going all the way
Server side JavaScript: going all the way
 
Venkat ns2
Venkat ns2Venkat ns2
Venkat ns2
 
Go and Uber’s time series database m3
Go and Uber’s time series database m3Go and Uber’s time series database m3
Go and Uber’s time series database m3
 
Skyline queries
Skyline queriesSkyline queries
Skyline queries
 
Samantha Wang [InfluxData] | Best Practices on How to Transform Your Data Usi...
Samantha Wang [InfluxData] | Best Practices on How to Transform Your Data Usi...Samantha Wang [InfluxData] | Best Practices on How to Transform Your Data Usi...
Samantha Wang [InfluxData] | Best Practices on How to Transform Your Data Usi...
 
Continuous Application with Structured Streaming 2.0
Continuous Application with Structured Streaming 2.0Continuous Application with Structured Streaming 2.0
Continuous Application with Structured Streaming 2.0
 
Data Analytics and Simulation in Parallel with MATLAB*
Data Analytics and Simulation in Parallel with MATLAB*Data Analytics and Simulation in Parallel with MATLAB*
Data Analytics and Simulation in Parallel with MATLAB*
 

Recently uploaded

May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
Shane Coughlan
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
Hornet Dynamics
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
TheSMSPoint
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
Green Software Development
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
Rakesh Kumar R
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
Neo4j
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
Ayan Halder
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
SOCRadar
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Łukasz Chruściel
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Crescat
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
Łukasz Chruściel
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
rodomar2
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
Green Software Development
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)
Boni García
 

Recently uploaded (20)

May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
 
Using Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional SafetyUsing Xen Hypervisor for Functional Safety
Using Xen Hypervisor for Functional Safety
 
socradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdfsocradar-q1-2024-aviation-industry-report.pdf
socradar-q1-2024-aviation-industry-report.pdf
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CDKuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
KuberTENes Birthday Bash Guadalajara - Introducción a Argo CD
 
Energy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina JonuziEnergy consumption of Database Management - Florina Jonuzi
Energy consumption of Database Management - Florina Jonuzi
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)
 

Concurrency in Go by Denys Goldiner.pdf

  • 1. Concurrency under the hood by Denys Goldiner
  • 2. Concurrency under the hood by Denys Goldiner
  • 4. Practical concurrency and some theory behind it by Denys Goldiner
  • 5. What is concurrency? - asynchrony - goroutines - synchronization - shared memory - message communication - execution planning - scheduler
  • 6. Questions I had in practice - is sync.Mutex absolutely safe? - how much does shared memory cost? - what is the secret of a nil channel? - is channel absolutely safe? - how to plan execution? - how to rule the concurrency? - how many goroutines do you need?
  • 8. Data race with mutex func main() { var wg sync.WaitGroup ctx, cancel := context.WithCancel(context.Background()) wg.Add(2) go checkCtxErr(&wg, ctx) go checkCtxVal(&wg, ctx) time.Sleep(1 * time.Second) cancel() wg.Wait() }
  • 9. Data race with mutex func checkCtxErr(wg *sync.WaitGroup, ctx context.Context) { defer wg.Done() for { select { case <-ctx.Done(): return default: if err := ctx.Err(); err != nil { return } } } }
  • 10. Data race with mutex func checkCtxVal(wg *sync.WaitGroup, ctx context.Context) { defer wg.Done() expectedCtx, _ := context.WithCancel(context.Background()) for { select { case <-ctx.Done(): return default: if reflect.DeepEqual(expectedCtx, ctx) { return } } } }
  • 11. Data race with mutex WARNING: DATA RACE - Read by goroutine 7: - reflect.deepValueEqual() - reflect.DeepEqual() - main.checkCtxVal() - Previous write by goroutine 6: - sync/atomic.CompareAndSwapInt32() - sync.(*Mutex).Lock() - context.(*cancelCtx).Done() - main.checkCtxErr()
  • 12. Data race with mutex type cancelCtx struct { Context mu sync.Mutex done chan struct{} children map[canceler]struct{} err error } func (c *cancelCtx) Err() error { c.mu.Lock() err := c.err c.mu.Unlock() return err }
  • 13. Be careful with reflect!
  • 14. How much does shared memory cost?
  • 15. False sharing, cache invalidation (core i7-9xxx) L3 cache L2 cache L2 cache Main Memory core1core2core3core4 L1 I-cache L1 D-cache T0 T1 L1 I-cache L1 D-cache T0 T1 L2 cache L1 I-cache L1 D-cache T0 T1 L2 cache L1 I-cache L1 D-cache T0 T1
  • 16. False sharing, cache invalidation func main() { arr := make([]int, 1000) wg := sync.WaitGroup{} wg.Add(len(arr)) for i := 0; i < len(arr); i++ { go func(wg *sync.WaitGroup, i int) { arr[i] = i * i wg.Done() }(&wg, i) } wg.Wait() }
  • 17. Map + sync.RWMutex type safeMap struct { data map[int]struct{} sync.RWMutex } func (sm *safeMap) check(v int) bool { sm.RLock() _, ok := sm.data[v] sm.RUnlock() return ok }
  • 18. Map + sync.RWMutex func mapUse(n int) { var sm = &safeMap{data: map[int]struct{}{0: {}, 1: {}, 2: {}}} var wg sync.WaitGroup wg.Add(n) for i := 0; i < n; i++ { go func(wg *sync.WaitGroup) { _ = sm.check(i % 3) wg.Done() }(&wg) } wg.Wait() }
  • 19. Map + mutex vs sync.Map cores iterations map + sync.RWMutex sync.Map
  • 20. Sync.Map use cases - stable keys - once written, many times read - many threads
  • 21. How to avoid false sharing?
  • 23. Using message communication func communication(arr []int) { ch := make(chan update) for i := 0; i < len(arr); i++ { go func(ch chan update, i int) { ch <- update{id: i, val: i * i} }(ch, i) } for j := 0; j < len(arr); j++ { iu := <-ch arr[iu.id] = iu.val } }
  • 24. What is the secret of a nil channel?
  • 25. Nil channel func main() { ch1 := make(chan struct{}) ch2 := make(chan struct{}) var wg sync.WaitGroup wg.Add(1) go fanIn(&wg, ch1, ch2) close(ch1) time.Sleep(1 * time.Second) close(ch2) wg.Wait() }
  • 26. Nil channel func fanIn(wg *sync.WaitGroup, ch1, ch2 <-chan struct{}) { defer wg.Done() var b1, b2 bool for !b1 || !b2 { select { case _, ok := <-ch1: if !ok { b1 = true } fmt.Println("case 1") case _, ok := <-ch2: if !ok { b2 = true } fmt.Println("case 2") } } }
  • 27. Nil channel - case 1 - case 1 - case 1 - case 1 - ... - case 1 - case 1 - case 1 - case 1 - case 2 - Process finished with exit code 0
  • 28. Nil channel func fanInUpgrade(wg *sync.WaitGroup, ch1, ch2 <-chan struct{}) { defer wg.Done() for ch1 != nil || ch2 != nil { select { case _, ok := <-ch1: if !ok { ch1 = nil } fmt.Println("case 1") case _, ok := <-ch2: if !ok { ch2 = nil } fmt.Println("case 2") } } }
  • 29. Nil channel - case 1 - case 2 - Process finished with exit code 0
  • 31. Data race with channel func main() { ch := make(chan struct{}) go func() { <-ch }() ch = nil } // data race
  • 32. Data race with channel func main() { ch := make(chan struct{}) go func(ch chan struct{}) { <-ch }(ch) ch = nil } // no data race
  • 33. Data race with channel func main() { ch := make(chan struct{}) go func(ch *chan struct{}) { <-*ch }(&ch) ch = nil } // data race
  • 34. Channels type hchan struct { qcount uint // total data in the queue dataqsiz uint // size of the circular queue buf unsafe.Pointer // points to an array of dataqsiz elements elemsize uint16 closed uint32 elemtype *_type // element type sendx uint // send index recvx uint // receive index recvq waitq // list of recv waiters sendq waitq // list of send waiters lock mutex }
  • 35. Data race with channel func makechan(t *chantype, size int) *hchan { … } func makemap(t *maptype, hint int, h *hmap) *hmap { … } func makeslice(et *_type, len, cap int) unsafe.Pointer { … }
  • 36. Data race with channel func main() { ch := make(chan struct{}) go func(ch chan struct{}) { ch = nil }(ch) log.Println(ch == nil) // false } func main() { ch := make(chan struct{}) go func(ch chan struct{}) { log.Println(ch == nil) // false }(ch) ch = nil }
  • 37. Take it in mind using nil in select
  • 38. Data race with data from channel func dataRace() { ch := make(chan *int) go func() { b := <-ch *b++ }() var a = 5 ch <- &a a++ }
  • 39. Pay attention to pointers
  • 40. How to plan execution?
  • 41. Scheduler (execution planning) - processor threads - OS threads - scheduler - context switch - software threads
  • 42. What is an execution context? It’s a number of registers needed to restore the thread execution: - Program Counter (PC) - Stack Pointer (SP) - …
  • 43. What is an execution context? - context switch is not for free! - we need a predictable execution context switch
  • 44. Statement of a problem - CPU-bound (working) - MAXIMIZE - workload for all available threads - MAXIMIZE - IO-bound (waiting) - MINIMIZE - execution context switching - MINIMIZE
  • 45. We need our own scheduler
  • 51. - 1/61 off the time, check global queue - check local queue - try to steal half of work from other P - check the global queue - poll network Work steal & GRQ
  • 56. How to rule the concurrency?
  • 57. Channels and FIFO - FIFO read goroutine queue - FIFO write goroutine queue - FIFO buffer
  • 58. Channels and FIFO - FIFO read goroutine queue - FIFO write goroutine queue - FIFO buffer
  • 59. Context switch conditions - GC - system calls (blocking / non-blocking / Cgo) - function calls - goroutine creation - synchronization operations - special function runtime.Gosched() It means other goroutines might start execution
  • 60. GOMAXPROCS - sets P number - for go run - for tests (go test -cpu <number>)
  • 61. How many goroutines do you need?
  • 62. How many goroutines do you need? - small amount of goroutines is bad - huge amount of goroutines is bad
  • 63. How many goroutines do you need? - type of work (IO / CPU bound) - how many blocking operations do you have - how many threads do you have - how much garbage does your program produce
  • 64. The amount of goroutines is an empirical value
  • 65. Bonus: 7 steps to effective concurrency - finish synchronous version of the program - write benchmarks to measure results - optimize synchronous implementation - check if your solution fits for concurrency - make your code concurrent - measure results - optimize concurrent implementation
  • 66. Links - https://habr.com/ru/post/338718/ - https://www.ardanlabs.com/blog/2018/08/scheduling-in-go-part1.html - https://medium.com/@riteeksrivastava/a-complete-journey-with-goroutines-8472630c7f5c - https://www.youtube.com/watch?v=t9bEg2A4jsw