Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
How not to Go wrong with concurrency – Artemiy ...
Search
Sponsored
·
Ship Features Fearlessly
Turn features on and off without deploys. Used by thousands of Ruby developers.
→
GopherCon Russia
April 13, 2019
Programming
70
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
How not to Go wrong with concurrency – Artemiy Ryabinkov
GopherCon Russia
April 13, 2019
More Decks by GopherCon Russia
See All by GopherCon Russia
Go Profiling from Bottom Up - Felix Geisendörfer
gopherconrussia
0
260
Learning Unsung Gotchas of Go - Rashmi Nagpal
gopherconrussia
1
300
Прозрачный gRPC-proxy один-ко-многим - Андрей Смирнов
gopherconrussia
0
180
Из Python в Go и обратно - Андрей Минкин
gopherconrussia
0
190
Оптимизация работы с PostgreSQL в Go: от 50 до 5000 RPS - Иван Осадчий
gopherconrussia
0
220
Пакет embed: распаковка знаний - Илья Данилкин
gopherconrussia
0
290
За пару мгновений до main() - Олег Ковалев
gopherconrussia
0
170
Тестирование в Go c Ginkgo и Gomega - Александр Егурнов
gopherconrussia
0
160
Building an Autoscaling HTTP Proxy for Kubernetes - Aaron Schlesinger
gopherconrussia
0
160
Other Decks in Programming
See All in Programming
<title><a id="</title>君はこのHTMLをパースできるか"></a></title> #雑LT_study
pizzacat83
0
150
Augmenting AI with the Power of Jakarta EE
ivargrimstad
0
620
ルールを書いて終わらせないハーネスエンジニアリング
yug1224
5
1.9k
言葉の格闘技のススメ~紙とペンと言葉から始める、キャリアの描き方~
progresscicada
2
150
そこに3びきプロダクトがいるじゃろう——生成AI時代における“価値が届かない理由”の構造
kosuket
0
500
freee が目指す データ マネジメント戦略 AI-Ready 時代を支える 攻めのガバナンスとは
freee
PRO
0
400
仕様駆動開発の消費期限
watany
20
8.5k
使いながら育てる Claude Code — 開発フローの1コマンド化 × 繰り返し指摘の自動仕組み化
shiki_kakaku
0
1.8k
Claude Code全社展開のためにやったことn選~プラグイン302個・コミッター271人を支えるために~
kenchan
5
1.5k
20260722_microCMSで考える、AI時代のコンテンツ運用設計
yosh1
0
410
yield再入門 #phpcon
o0h
PRO
0
1.1k
自動化したのに回らないテスト運用の壁ーAI時代の品質責任と生産性
mfunaki
1
140
Featured
See All Featured
For a Future-Friendly Web
brad_frost
183
10k
Rails Girls Zürich Keynote
gr2m
96
14k
How To Stay Up To Date on Web Technology
chriscoyier
790
250k
VelocityConf: Rendering Performance Case Studies
addyosmani
332
25k
AI Search: Implications for SEO and How to Move Forward - #ShenzhenSEOConference
aleyda
1
1.3k
Practical Orchestrator
shlominoach
191
12k
The Cost Of JavaScript in 2023
addyosmani
55
10k
How to Align SEO within the Product Triangle To Get Buy-In & Support - #RIMC
aleyda
2
1.8k
Optimizing for Happiness
mojombo
378
71k
The Organizational Zoo: Understanding Human Behavior Agility Through Metaphoric Constructive Conversations (based on the works of Arthur Shelley, Ph.D)
kimpetersen
PRO
0
410
Skip the Path - Find Your Career Trail
mkilby
1
180
A Tale of Four Properties
chriscoyier
163
24k
Transcript
How not to Go wrong with concurrency Artemiy Ryabinkov
None
Go is expressive, concise, clean, and efficient. Its concurrency mechanisms
make it easy to write programs that get the most out of multicore and networked machines. golang.org/doc/
Two Models of Communication Shared Memory Message Passing (CSP and
Actor Model) Locks Mutexes Implicit communication Messages Channels Explicit communication
Do not communicate by sharing memory; instead, share memory by
communicating.
Communicating Sequential Processes
Application Shared Memory Message Passing Mutex RWMutex Wait Chan Chan
+ other ops Lib Docker 9 0 3 5 2 2 Kubernetes 6 2 0 3 6 0 etcd 5 0 0 10 5 1 CockroachDB 4 3 0 5 0 0 gRPC 2 0 0 6 2 1 BoltDB 2 0 0 0 1 0 Total 28 5 3 29 16 4 Blocking Bug Causes https://songlh.github.io/paper/go-study.pdf
https://songlh.github.io/paper/go-study.pdf Our study found that message passing does not necessarily
make multithreaded programs less error-prone than shared memory. In fact, message passing is the main cause of blocking bugs.
Concurrency Parallelism
None
Amdahl’s law
Speedup( P processors ) = Time( 1 processor ) Time(
P processors ) F = inherently sequential fraction of the computation 1+(P-1)F S MAX = P
F = 1% F = 5% F = 10% Max
Speedup Processors 40 32 24 16 8 8 16 24 32 40 48 56 64
Some programs are nicer even if not parallel at all
Synchronization Context Switch Network Request Memory Allocation Disk Read/Write Garbage
Collection
CPU Bound IO Bound Progress is limited by CPU speed
Progress is limited by I/O subsystem speed
Core Cache Line Memory
False Cache-Line Sharing
Core 0 Cache Line Core 1 Cache Line Memory
None
Scheduler
UserSpace Scheduler OS Scheduler CPU
Cooperative multitasking Preemptive multitasking Process makes switch decision Process can
monopolize processor Effective context switch Scheduler makes switch decision Prevents monopolizing Overheads involved with interrupts Fair timeslice
UserSpace Scheduler OS Scheduler CPU Preemptive Preemptive
UserSpace Scheduler OS Scheduler CPU Preemptive Cooperative Gooperative
runtime.GOMAXPROCS(1) x := 0 go func() { for { x++
} }() time.Sleep(500 * time.Millisecond) fmt.Println(x)
runtime.GOMAXPROCS(1) x := 0 go func() { for { runtime.Gosched()
x++ } }() time.Sleep(500 * time.Millisecond) fmt.Println(x)
runtime.morestack() -> runtime.newstack() runtime.Gosched() locks network I/O syscalls Goroutine preemption
points Cyrill Lashkevich - Go Scheduler
Race Conditions
a += 1
a += 1 tmp = a + 1 a =
tmp ⇔
a += 1 if a == 1 { criticalSection() }
a += 1 if a == 1 { criticalSection() }
tmp = a+1 a = tmp if a == 1
{ criticalSection() } tmp = a+1 a = tmp if a == 1 { criticalSection() }
var mx sync.Mutex // .. mx.Lock() tmp = a +
1 a = tmp if a == 1 { criticalSection() } mx.Unlock()
mx.Lock() tmp = a + 1 a = tmp mx.Unlock()
atomic.AddInt64(&a, 1) ⇔
atomic.AddInt64(&a, 1) val = atomic.LoadInt64(&a)
func setup() { a = "hello, world" done = true
} var once sync.Once func doprint() { if !done { once.Do(setup) } print(a) }
func setup() { done = true a = "hello, world"
} var once sync.Once func doprint() { if !done { once.Do(setup) } print(a) }
The Go Memory Model https://golang.org/ref/mem Benign Data Races: What Could
Possibly Go Wrong? https://intel.ly/1MaL4rD
Deadlock
mx1.Lock() mx2.Lock() mx2.Lock() mx1.Lock()
mx1.Lock() mx2.Lock() mx1.Lock() mx2.Lock()
m.Lock() m.Unlock() request <- ch m.Lock() ch <- request m.Unlock()
The Deadlock Empire https://deadlockempire.github.io/
Race Conditions Deadlock/Livelock Starvation False Sharing/Lock Contention Sort of Problems
Race Detector go test -race
Requires test coverage Stores history of N memory access Reports
no false positives. May miss data races Limits of Race Detector
ThreadSanitizerAlgorithm https://bit.ly/2WctkVx Data Race Detector: official docs https://bit.ly/2TXlTEe
Block profile go test -run=XXX -bench=. --blockprofile=block.out go tool pprof
http://.../debug/pprof/block
Let's Code On
func call(ctx context.Context, requests []T) error { for _, req
:= range requests { err := send(ctx, req) if err != nil { return err } } return nil }
func call(ctx context.Context, requests []T) error { errCh := make(chan
error, 1) var wg sync.WaitGroup for _, req := range requests { go func() { wg.Add(1) if err = send(ctx, req); err != nil { errCh <- err } wg.Done() }() } wg.Wait() close(errCh) return <-errCh }
for _, req := range requests { go func() {
wg.Add(1) if err = send(ctx, req); err != nil { errCh <- err } wg.Done() }() } wg.Wait() close(errCh) return <-errCh
for _, req := range requests { go func() {
wg.Add(1) if err = send(ctx, req); err != nil { errCh <- err } wg.Done() }() } wg.Wait() close(errCh) return <-errCh
wg.Add(len(requests)) for _, req := range requests { go func()
{ if err = send(ctx, req); err != nil { errCh <- err } wg.Done() }() } wg.Wait() close(errCh) return <-errCh
wg.Add(len(requests)) for _, req := range requests { go func()
{ if err = send(ctx, req); err != nil { errCh <- err } wg.Done() }() } wg.Wait() close(errCh) return <-errCh
wg.Add(len(requests)) for _, req := range requests { go func(req
T) { if err = send(ctx, req); err != nil { errCh <- err } wg.Done() }(req) } wg.Wait() close(errCh) return <-errCh
errCh := make(chan error, 1) for _, req := range
requests { go func() { if err = send(ctx, req); err != nil { errCh <- err } }() } ... return <-errCh
errCh := make(chan error, 1) for _, req := range
requests { go func() { if err = send(ctx, req); err != nil { errCh <- err } }() } return <-errCh
errCh := make(chan error, len(requests)) for _, req := range
requests { go func() { if err = send(ctx, req); err != nil { errCh <- err } }() } return <-errCh
func call(ctx context.Context, requests []T) error { errCh := make(chan
error, len(requests)) var wg sync.WaitGroup wg.Add(len(requests)) for _, req := range requests { go func(req string) { if err = send(ctx, req); err != nil { errCh <- err } wg.Done() }(req) } wg.Wait() close(errCh) return <-errCh } Dave Cheney: Concurrency made easy
golang.org/x/sync/errgroup
func call(ctx context.Context, requests []T) error { g, ctx :=
errgroup.WithContext(ctx) for _, req := range requests { req := req g.Go(func() error { return send(ctx, req) }) } return g.Wait() }
func call(ctx context.Context, requests []T) error { for _, req
:= range requests { err := send(ctx, req) if err != nil { return err } } return nil }
ctx := context.Background() g, ctx := errgroup.WithContext(ctx) g.Go(func() error {
return DoA(ctx) }) g.Go(func() error { return DoB(ctx) }) err := g.Wait()
As Simple as Possible, but not Simpler Get to know
your abstractions Explicit over implicit syncronization
Go ❤ Concurrency
Artemiy Ryabinkov github.com/furdarius
[email protected]
facebook.com/furdarius