SlideShare a Scribd company logo
1 of 40
Download to read offline
Concurrency
Golang #2
Vu Nguyen
vu.nguyen@will.vn
Why Go?
1. Single binary deployment
2. Minimal language
3. Easy concurrency
4. Full development environment
5. Multi-arch build
6. Low-level interface
7. Getting started quickly
Why Go?
1. Single binary deployment
2. Minimal language
3. Easy concurrency
4. Full development environment
5. Multi-arch build
6. Low-level interface
7. Getting started quickly
JavaScript
function *fibo() {
let a = 0, b = 1;
while (true) {
yield a;
[a, b] = [b, a+b];
}
}
for (let value of fibo()) {
console.log(value);
};
JavaScript
function *fibo() {
let a = 0, b = 1;
while (true) {
yield a;
[a, b] = [b, a+b];
}
}
for (let value of fibo()) {
console.log(value);
};
Single thread !
Golang
func fibo(ch chan<- int) {
a, b := 0, 1
for {
ch <- a
a, b = b, a + b
}
}
func main() {
ch := make(chan int)
go fibo(ch)
for i:= 0; i < 10; i++ {
fi := <- ch
println(fi)
}
}
Run
Golang
func fibo(ch chan<- int) {
a, b := 0, 1
for true {
ch <- a
a, b = b, a + b
}
}
func main() {
ch := make(chan int)
go fibo(ch)
for i:= 0; i < 10; i++ {
fi := <- ch
println(fi)
}
}
$ export GOMAXPROCS=4
Run
Concurrency
Golang #2
Concurrency in Go
1. What is concurrency?
2. Communicating with channel & select
3. Atomic accessing with mutex.Lock()
4. Detecting race condition with go race
5. Examples
What is concurrency?
Concurrency is the composition of independently executing
computations.
Concurrency is a way to structure software, particularly as
a way to write clean code that interacts well with the real
world.
It is not parallelism.
What is concurrency?
ConcurrencyParallelism
(withoutparallelism)
Time
Goroutine
It's an independently executing function, launched by a go
statement.
It has its own call stack, which grows and shrinks as required.
It's very cheap. It's practical to have thousands, even
hundreds of thousands of goroutines.
It's not a thread.
Goroutine
Example: Hello
func hello(name string) {
for {
fmt.Println(“Hello from”, name)
time.Sleep(200 * time.Millisecond)
}
}
func main() {
go hello(“Alice”)
go hello(“Bob”)
time.Sleep(1000 * time.Millisecond)
}
Run
Communication
channel & select
c := make(chan int) – Makes an unbuffered channel of ints
c <- x – Sends a value on the channel
<- c – Waits to receive a value on the channel
x = <- c – Waits to receive a value and stores it in x
x, ok = <- c – ok will be false if channel is closed
close(c) – Mark a channel not available to use
Channel
Example: Hello channel
func hello(name string) chan string {
c := make(chan string)
go func() {
for {
c <- “Hello from “ + name
time.Sleep(100 * time.Millisecond)
}
}()
return c
}
func main() {
a := hello(“Alice”)
b := hello(“Bob”)
for i := 0; i < 5; i++ {
fmt.Println(<-a)
fmt.Println(<-b)
}
}
Run
Example: Multi-flexing
func fanIn(c1, c2 <-chan string) <-chan string {
c := make(chan string)
go func(){ for { c <- <-c1 } }()
go func(){ for { c <- <-c2 } }()
return c
}
func main() {
c := fanIn(hello(“Alice”), hello(“Bob”))
for i:= 0; i < 10; i++ {
fmt.Println(<-c)
}
}
Run
Example: Fibonacci
func fibo(ch chan<- int) {
a, b := 0, 1
for true {
ch <- a
a, b = b, a + b
}
}
func main() {
ch := make(chan int)
go fibo(ch)
for i:= 0; i < 10; i++ {
fi := <- ch
println(fi)
}
}
Run
Example: Unique ID service
func startIdService() chan int {
c := make(chan int)
counter := 0
go func() {
for {
counter++
c <- counter
}
}()
return c
}
func main() {
c := startIdService()
id1 := <- c
id2 := <- c
fmt.Println(id1, id2)
}
Run
select { // Try executing each statement until one is available
case <- c1: // Try reading from c1
case x := <- c2 // Try reading from c2 to x
case c3 <- value // Try sending to c3
default: // Run if no other statement available
}
Select
Example: Hello channel & select
func hello(name string) chan string {
c := make(chan string)
go func() {
for i := 0; i < 5; i++ {
c <- “Hello from “ + name
time.Sleep(100 * time.Millisecond)
}
}()
return c
}
func main() {
a := hello(“Alice”)
b := hello(“Bob”)
for {
select {
case v, ok := <-a:
if !ok {
return
}
fmt.Println(v)
}
}
Run
Example: First response
func get(c chan string, url string) {
if res, err := http.Get(url); err == nil {
data, _ := ioutil.ReadAll(res.Body))
c <- string(data)
}
}
func main() {
first := make(chan string)
for _, url := range []string{ “http://example.com”, “http://google.com” } {
go get(first, url)
}
body := <- first
}
Example: Timeout
func timeout(t time.Duration) <-chan int {
c := make(chan int)
go func() {
time.Sleep(t)
close(c)
}()
return c
}
Run
func main() {
chTime := timeout(time.Second)
chBody := make(chan string)
go get(“http://example.com”)
select {
case body := <-chBody
fmt.Println(body)
case <-chTime:
fmt.Println(“Timeout!”)
}
}
Atomic access
mutex.Lock()
var m sync.Mutex // Make a new mutex
m.Lock()
m.Unlock()
// Code between Lock() and Unlock() can only be executed in
one goroutine at the same time.
mutex.Lock()
Example: Lock() - 1
var a = make([]int, 0)
func add(i int) {
time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond)
a = append(a, i)
}
func main() {
for i := 0; i < 10; i++ {
go add(i)
}
time.Sleep(time.Second)
fmt.Println(a)
}
Run
Example: Lock() - 2
var a = make([]int, 0)
var m sync.Mutex
func add(i int) {
m.Lock()
defer m.Unlock()
time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond)
a = append(a, i)
}
Run
Example: Wait Group
var wg sync.WaitGroup
var urls = []string{ “http://www.golang.org/”, “http://www.google.com/” }
for _, url := range urls {
wg.Add(1)
go func(url string) {
defer wg.Done()
http.Get(url)
}(url)
}
wg.Wait()
Detecting race condition
go race
Detecting race condition
go run -race sample.go
go test -race sample
go build -race sample
go get -race sample
Sample output
$ go run -race examples/race.go
==================
WARNING: DATA RACE
Read by goroutine 10:
main.add()
/home/i/x/src/go2/examples/race.go:18 +0x5a
Previous write by goroutine 14:
main.add()
/home/i/x/src/go2/examples/race.go:18 +0x12a
Rules
- Use channel to synchronize between goroutine
- Only one goroutine can read and write a variable
+ Or use mutex.Lock()
- close(c): Use like sending an EOF value. Only sending
goroutine should call close()
Rules
Thanks for your listening
Golang #2: Concurrency
Vu Nguyen
vu.nguyen@will.vn
- https://blog.golang.org/share-memory-by-communicating
- https://blog.golang.org/concurrency-is-not-parallelism
- http://talks.golang.org/2012/concurrency.slide
- http://talks.golang.org/2013/advconc.slide
- http://gary.burd.info/go-websocket-chat
Read more

More Related Content

What's hot

What's hot (20)

Go Lang Tutorial
Go Lang TutorialGo Lang Tutorial
Go Lang Tutorial
 
golang_getting_started.pptx
golang_getting_started.pptxgolang_getting_started.pptx
golang_getting_started.pptx
 
Go. Why it goes
Go. Why it goesGo. Why it goes
Go. Why it goes
 
The Go programming language - Intro by MyLittleAdventure
The Go programming language - Intro by MyLittleAdventureThe Go programming language - Intro by MyLittleAdventure
The Go programming language - Intro by MyLittleAdventure
 
Golang
GolangGolang
Golang
 
Introduction to Coroutines @ KotlinConf 2017
Introduction to Coroutines @ KotlinConf 2017Introduction to Coroutines @ KotlinConf 2017
Introduction to Coroutines @ KotlinConf 2017
 
Golang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageGolang - Overview of Go (golang) Language
Golang - Overview of Go (golang) Language
 
Introduction to Go programming language
Introduction to Go programming languageIntroduction to Go programming language
Introduction to Go programming language
 
Write microservice in golang
Write microservice in golangWrite microservice in golang
Write microservice in golang
 
Why you should care about Go (Golang)
Why you should care about Go (Golang)Why you should care about Go (Golang)
Why you should care about Go (Golang)
 
An Actor Model in Go
An Actor Model in GoAn Actor Model in Go
An Actor Model in Go
 
Introduction to go lang
Introduction to go langIntroduction to go lang
Introduction to go lang
 
Coding with golang
Coding with golangCoding with golang
Coding with golang
 
GO programming language
GO programming languageGO programming language
GO programming language
 
Kotlin Coroutines Reloaded
Kotlin Coroutines ReloadedKotlin Coroutines Reloaded
Kotlin Coroutines Reloaded
 
[COSCUP 2022] Kotlin Collection 遊樂園
[COSCUP 2022] Kotlin Collection 遊樂園[COSCUP 2022] Kotlin Collection 遊樂園
[COSCUP 2022] Kotlin Collection 遊樂園
 
GoLang Introduction
GoLang IntroductionGoLang Introduction
GoLang Introduction
 
Golang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / OverviewGolang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / Overview
 
Golang 101
Golang 101Golang 101
Golang 101
 
Golang (Go Programming Language)
Golang (Go Programming Language)Golang (Go Programming Language)
Golang (Go Programming Language)
 

Similar to Concurrency in Golang

Similar to Concurrency in Golang (20)

Go ahead, make my day
Go ahead, make my dayGo ahead, make my day
Go ahead, make my day
 
Go vs C++ - CppRussia 2019 Piter BoF
Go vs C++ - CppRussia 2019 Piter BoFGo vs C++ - CppRussia 2019 Piter BoF
Go vs C++ - CppRussia 2019 Piter BoF
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in Golang
 
Something about Golang
Something about GolangSomething about Golang
Something about Golang
 
Erlang bootstrap course
Erlang bootstrap courseErlang bootstrap course
Erlang bootstrap course
 
Go Concurrency Patterns
Go Concurrency PatternsGo Concurrency Patterns
Go Concurrency Patterns
 
Go concurrency
Go concurrencyGo concurrency
Go concurrency
 
Concurrency in Python4k
Concurrency in Python4kConcurrency in Python4k
Concurrency in Python4k
 
Non Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJavaNon Blocking I/O for Everyone with RxJava
Non Blocking I/O for Everyone with RxJava
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
Current State of Coroutines
Current State of CoroutinesCurrent State of Coroutines
Current State of Coroutines
 
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
 
GoLightly: Building VM-Based Language Runtimes with Google Go
GoLightly: Building VM-Based Language Runtimes with Google GoGoLightly: Building VM-Based Language Runtimes with Google Go
GoLightly: Building VM-Based Language Runtimes with Google Go
 
Are we ready to Go?
Are we ready to Go?Are we ready to Go?
Are we ready to Go?
 
The Ring programming language version 1.10 book - Part 22 of 212
The Ring programming language version 1.10 book - Part 22 of 212The Ring programming language version 1.10 book - Part 22 of 212
The Ring programming language version 1.10 book - Part 22 of 212
 
Google Go For Ruby Hackers
Google Go For Ruby HackersGoogle Go For Ruby Hackers
Google Go For Ruby Hackers
 
Building a DRYer Android App with Kotlin
Building a DRYer Android App with KotlinBuilding a DRYer Android App with Kotlin
Building a DRYer Android App with Kotlin
 
Introduction to go
Introduction to goIntroduction to go
Introduction to go
 
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel ZikmundNDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
 
The Ring programming language version 1.5.3 book - Part 25 of 184
The Ring programming language version 1.5.3 book - Part 25 of 184The Ring programming language version 1.5.3 book - Part 25 of 184
The Ring programming language version 1.5.3 book - Part 25 of 184
 

More from Oliver N

More from Oliver N (10)

High productivity web development workflow - JavaScript Meetup Saigon 2014
High productivity web development workflow - JavaScript Meetup Saigon 2014High productivity web development workflow - JavaScript Meetup Saigon 2014
High productivity web development workflow - JavaScript Meetup Saigon 2014
 
WebRTC: Bring real-time to the web - Barcamp Saigon 2012
WebRTC: Bring real-time to the web - Barcamp Saigon 2012WebRTC: Bring real-time to the web - Barcamp Saigon 2012
WebRTC: Bring real-time to the web - Barcamp Saigon 2012
 
New trends of web technology on mobile: HTML5, PhoneGap & NaCl - Barcamp Saig...
New trends of web technology on mobile: HTML5, PhoneGap & NaCl - Barcamp Saig...New trends of web technology on mobile: HTML5, PhoneGap & NaCl - Barcamp Saig...
New trends of web technology on mobile: HTML5, PhoneGap & NaCl - Barcamp Saig...
 
What does people say when they switch to Go?
What does people say when they switch to Go?What does people say when they switch to Go?
What does people say when they switch to Go?
 
Grokking #9: Building a real-time and offline editing service with Couchbase
Grokking #9: Building a real-time and offline editing service with CouchbaseGrokking #9: Building a real-time and offline editing service with Couchbase
Grokking #9: Building a real-time and offline editing service with Couchbase
 
The fundamental problems of GUI applications and why people choose React
The fundamental problems of GUI applications and why people choose ReactThe fundamental problems of GUI applications and why people choose React
The fundamental problems of GUI applications and why people choose React
 
Litibook - Feb 2016
Litibook - Feb 2016Litibook - Feb 2016
Litibook - Feb 2016
 
Golang #5: To Go or not to Go
Golang #5: To Go or not to GoGolang #5: To Go or not to Go
Golang #5: To Go or not to Go
 
Modern Web Development in 2015
Modern Web Development in 2015Modern Web Development in 2015
Modern Web Development in 2015
 
Isomorphic web application
Isomorphic web applicationIsomorphic web application
Isomorphic web application
 

Recently uploaded

%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
masabamasaba
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
chiefasafspells
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 

Recently uploaded (20)

%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - Keynote
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaS
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
 

Concurrency in Golang

  • 2. Why Go? 1. Single binary deployment 2. Minimal language 3. Easy concurrency 4. Full development environment 5. Multi-arch build 6. Low-level interface 7. Getting started quickly
  • 3. Why Go? 1. Single binary deployment 2. Minimal language 3. Easy concurrency 4. Full development environment 5. Multi-arch build 6. Low-level interface 7. Getting started quickly
  • 4. JavaScript function *fibo() { let a = 0, b = 1; while (true) { yield a; [a, b] = [b, a+b]; } } for (let value of fibo()) { console.log(value); };
  • 5. JavaScript function *fibo() { let a = 0, b = 1; while (true) { yield a; [a, b] = [b, a+b]; } } for (let value of fibo()) { console.log(value); }; Single thread !
  • 6. Golang func fibo(ch chan<- int) { a, b := 0, 1 for { ch <- a a, b = b, a + b } } func main() { ch := make(chan int) go fibo(ch) for i:= 0; i < 10; i++ { fi := <- ch println(fi) } } Run
  • 7. Golang func fibo(ch chan<- int) { a, b := 0, 1 for true { ch <- a a, b = b, a + b } } func main() { ch := make(chan int) go fibo(ch) for i:= 0; i < 10; i++ { fi := <- ch println(fi) } } $ export GOMAXPROCS=4 Run
  • 9. Concurrency in Go 1. What is concurrency? 2. Communicating with channel & select 3. Atomic accessing with mutex.Lock() 4. Detecting race condition with go race 5. Examples
  • 11. Concurrency is the composition of independently executing computations. Concurrency is a way to structure software, particularly as a way to write clean code that interacts well with the real world. It is not parallelism. What is concurrency?
  • 12.
  • 13.
  • 15.
  • 17. It's an independently executing function, launched by a go statement. It has its own call stack, which grows and shrinks as required. It's very cheap. It's practical to have thousands, even hundreds of thousands of goroutines. It's not a thread. Goroutine
  • 18. Example: Hello func hello(name string) { for { fmt.Println(“Hello from”, name) time.Sleep(200 * time.Millisecond) } } func main() { go hello(“Alice”) go hello(“Bob”) time.Sleep(1000 * time.Millisecond) } Run
  • 20. c := make(chan int) – Makes an unbuffered channel of ints c <- x – Sends a value on the channel <- c – Waits to receive a value on the channel x = <- c – Waits to receive a value and stores it in x x, ok = <- c – ok will be false if channel is closed close(c) – Mark a channel not available to use Channel
  • 21. Example: Hello channel func hello(name string) chan string { c := make(chan string) go func() { for { c <- “Hello from “ + name time.Sleep(100 * time.Millisecond) } }() return c } func main() { a := hello(“Alice”) b := hello(“Bob”) for i := 0; i < 5; i++ { fmt.Println(<-a) fmt.Println(<-b) } } Run
  • 22. Example: Multi-flexing func fanIn(c1, c2 <-chan string) <-chan string { c := make(chan string) go func(){ for { c <- <-c1 } }() go func(){ for { c <- <-c2 } }() return c } func main() { c := fanIn(hello(“Alice”), hello(“Bob”)) for i:= 0; i < 10; i++ { fmt.Println(<-c) } } Run
  • 23. Example: Fibonacci func fibo(ch chan<- int) { a, b := 0, 1 for true { ch <- a a, b = b, a + b } } func main() { ch := make(chan int) go fibo(ch) for i:= 0; i < 10; i++ { fi := <- ch println(fi) } } Run
  • 24. Example: Unique ID service func startIdService() chan int { c := make(chan int) counter := 0 go func() { for { counter++ c <- counter } }() return c } func main() { c := startIdService() id1 := <- c id2 := <- c fmt.Println(id1, id2) } Run
  • 25. select { // Try executing each statement until one is available case <- c1: // Try reading from c1 case x := <- c2 // Try reading from c2 to x case c3 <- value // Try sending to c3 default: // Run if no other statement available } Select
  • 26. Example: Hello channel & select func hello(name string) chan string { c := make(chan string) go func() { for i := 0; i < 5; i++ { c <- “Hello from “ + name time.Sleep(100 * time.Millisecond) } }() return c } func main() { a := hello(“Alice”) b := hello(“Bob”) for { select { case v, ok := <-a: if !ok { return } fmt.Println(v) } } Run
  • 27. Example: First response func get(c chan string, url string) { if res, err := http.Get(url); err == nil { data, _ := ioutil.ReadAll(res.Body)) c <- string(data) } } func main() { first := make(chan string) for _, url := range []string{ “http://example.com”, “http://google.com” } { go get(first, url) } body := <- first }
  • 28. Example: Timeout func timeout(t time.Duration) <-chan int { c := make(chan int) go func() { time.Sleep(t) close(c) }() return c } Run func main() { chTime := timeout(time.Second) chBody := make(chan string) go get(“http://example.com”) select { case body := <-chBody fmt.Println(body) case <-chTime: fmt.Println(“Timeout!”) } }
  • 30. var m sync.Mutex // Make a new mutex m.Lock() m.Unlock() // Code between Lock() and Unlock() can only be executed in one goroutine at the same time. mutex.Lock()
  • 31. Example: Lock() - 1 var a = make([]int, 0) func add(i int) { time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond) a = append(a, i) } func main() { for i := 0; i < 10; i++ { go add(i) } time.Sleep(time.Second) fmt.Println(a) } Run
  • 32. Example: Lock() - 2 var a = make([]int, 0) var m sync.Mutex func add(i int) { m.Lock() defer m.Unlock() time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond) a = append(a, i) } Run
  • 33. Example: Wait Group var wg sync.WaitGroup var urls = []string{ “http://www.golang.org/”, “http://www.google.com/” } for _, url := range urls { wg.Add(1) go func(url string) { defer wg.Done() http.Get(url) }(url) } wg.Wait()
  • 35. Detecting race condition go run -race sample.go go test -race sample go build -race sample go get -race sample
  • 36. Sample output $ go run -race examples/race.go ================== WARNING: DATA RACE Read by goroutine 10: main.add() /home/i/x/src/go2/examples/race.go:18 +0x5a Previous write by goroutine 14: main.add() /home/i/x/src/go2/examples/race.go:18 +0x12a
  • 37. Rules
  • 38. - Use channel to synchronize between goroutine - Only one goroutine can read and write a variable + Or use mutex.Lock() - close(c): Use like sending an EOF value. Only sending goroutine should call close() Rules
  • 39. Thanks for your listening Golang #2: Concurrency Vu Nguyen vu.nguyen@will.vn
  • 40. - https://blog.golang.org/share-memory-by-communicating - https://blog.golang.org/concurrency-is-not-parallelism - http://talks.golang.org/2012/concurrency.slide - http://talks.golang.org/2013/advconc.slide - http://gary.burd.info/go-websocket-chat Read more