Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
How not to Go wrong with concurrency – Artemiy ...
Search
GopherCon Russia
April 13, 2019
Programming
75
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
270
Learning Unsung Gotchas of Go - Rashmi Nagpal
gopherconrussia
1
310
Прозрачный gRPC-proxy один-ко-многим - Андрей Смирнов
gopherconrussia
0
190
Из Python в Go и обратно - Андрей Минкин
gopherconrussia
0
190
Оптимизация работы с PostgreSQL в Go: от 50 до 5000 RPS - Иван Осадчий
gopherconrussia
0
230
Пакет embed: распаковка знаний - Илья Данилкин
gopherconrussia
0
310
За пару мгновений до main() - Олег Ковалев
gopherconrussia
0
180
Тестирование в Go c Ginkgo и Gomega - Александр Егурнов
gopherconrussia
0
170
Building an Autoscaling HTTP Proxy for Kubernetes - Aaron Schlesinger
gopherconrussia
0
170
Other Decks in Programming
See All in Programming
設計次第でAIコードの読む量は減らせる / designing-for-code-reading
minodriven
35
17k
S3 TablesのIcebergデータに、AIエージェントからアクセスしてみた / 20261016developersio2026joetsu-accessing-iceberg-in-s3tables-via-agent
kasacchiful
PRO
0
170
The Rails Doctrine Decade
koic
2
600
Next.js: The final boss of Web Performance
guaca
0
280
月間100万人のサービス刷新で、 技術選定をHonoに振り切った話
yutobara
8
6.7k
コードレビューのボトルネックを"する側"と"される側"の両面から解消する
yub0n
2
1.6k
UPDATE をやめる — EF Core でマスタをバージョン管理する
panda728
PRO
0
1.2k
JIS keyboard support in Omarchy
lef237
0
130
ハーネス設計入門 〜 基礎知識の整理から実務へのステップアップ 〜
kinopeee
28
33k
iOS 27でニュースアプリはどう変わる!? 〜日経電子版の新機能対応と、開発事例から〜
lynnswap
7
13k
golang-bob.pdf
iwatsukayura
0
130
[JA] Domain Modeling with Vanilla Rails: 「操作」から再考するRailsの設計論
yasaichi
3
440
Featured
See All Featured
30 Presentation Tips
portentint
PRO
1
430
Product Roadmaps are Hard
iamctodd
55
13k
Distributed Sagas: A Protocol for Coordinating Microservices
caitiem20
333
23k
The Art of Programming - Codeland 2020
erikaheidi
57
14k
Templates, Plugins, & Blocks: Oh My! Creating the theme that thinks of everything
marktimemedia
31
2.9k
Building Experiences: Design Systems, User Experience, and Full Site Editing
marktimemedia
1
630
Visual Storytelling: How to be a Superhuman Communicator
reverentgeek
2
710
CSS Pre-Processors: Stylus, Less & Sass
bermonpainter
360
31k
Joys of Absence: A Defence of Solitary Play
codingconduct
1
550
Technical Leadership for Architectural Decision Making
baasie
3
600
Building Better People: How to give real-time feedback that sticks.
wjessup
371
20k
My Coaching Mixtape
mlcsv
0
360
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