SlideShare ist ein Scribd-Unternehmen logo
1 von 40
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Golang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageGolang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageAniruddha Chakrabarti
 
Go Programming language, golang
Go Programming language, golangGo Programming language, golang
Go Programming language, golangBasil N G
 
Go Programming Language (Golang)
Go Programming Language (Golang)Go Programming Language (Golang)
Go Programming Language (Golang)Ishin Vin
 
Write microservice in golang
Write microservice in golangWrite microservice in golang
Write microservice in golangBo-Yi Wu
 
Go language presentation
Go language presentationGo language presentation
Go language presentationparamisoft
 
Asynchronous javascript
 Asynchronous javascript Asynchronous javascript
Asynchronous javascriptEman Mohamed
 
Introduction to go lang
Introduction to go langIntroduction to go lang
Introduction to go langAmal Mohan N
 
Go Programming Language by Google
Go Programming Language by GoogleGo Programming Language by Google
Go Programming Language by GoogleUttam Gandhi
 
JavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScriptJavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScriptLaurence Svekis ✔
 
Angular Data Binding
Angular Data BindingAngular Data Binding
Angular Data BindingDuy Khanh
 
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)Aaron Schlesinger
 
GO programming language
GO programming languageGO programming language
GO programming languagetung vu
 

Was ist angesagt? (20)

Golang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageGolang - Overview of Go (golang) Language
Golang - Overview of Go (golang) Language
 
Go Programming language, golang
Go Programming language, golangGo Programming language, golang
Go Programming language, golang
 
Go Programming Language (Golang)
Go Programming Language (Golang)Go Programming Language (Golang)
Go Programming Language (Golang)
 
Golang
GolangGolang
Golang
 
Write microservice in golang
Write microservice in golangWrite microservice in golang
Write microservice in golang
 
Go. Why it goes
Go. Why it goesGo. Why it goes
Go. Why it goes
 
Golang
GolangGolang
Golang
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
Go language presentation
Go language presentationGo language presentation
Go language presentation
 
Go Lang Tutorial
Go Lang TutorialGo Lang Tutorial
Go Lang Tutorial
 
Asynchronous javascript
 Asynchronous javascript Asynchronous javascript
Asynchronous javascript
 
Introduction to go lang
Introduction to go langIntroduction to go lang
Introduction to go lang
 
Go Programming Language by Google
Go Programming Language by GoogleGo Programming Language by Google
Go Programming Language by Google
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
Golang workshop
Golang workshopGolang workshop
Golang workshop
 
JavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScriptJavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScript
 
Angular Data Binding
Angular Data BindingAngular Data Binding
Angular Data Binding
 
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)
 
Javascript
JavascriptJavascript
Javascript
 
GO programming language
GO programming languageGO programming language
GO programming language
 

Ähnlich wie Concurrency in Golang

Go ahead, make my day
Go ahead, make my dayGo ahead, make my day
Go ahead, make my dayTor Ivry
 
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 BoFTimur Safin
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in GolangBo-Yi Wu
 
Something about Golang
Something about GolangSomething about Golang
Something about GolangAnton Arhipov
 
Erlang bootstrap course
Erlang bootstrap courseErlang bootstrap course
Erlang bootstrap courseMartin Logan
 
Go Concurrency Patterns
Go Concurrency PatternsGo Concurrency Patterns
Go Concurrency PatternsElifTech
 
Go concurrency
Go concurrencyGo concurrency
Go concurrencysiuyin
 
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 RxJavaFrank Lyaruu
 
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)Pavlo Baron
 
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...Víctor Bolinches
 
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 GoEleanor McHugh
 
Are we ready to Go?
Are we ready to Go?Are we ready to Go?
Are we ready to Go?Adam Dudczak
 
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 212Mahmoud Samir Fayed
 
Google Go For Ruby Hackers
Google Go For Ruby HackersGoogle Go For Ruby Hackers
Google Go For Ruby HackersEleanor McHugh
 
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 KotlinBoonya Kitpitak
 
Introduction to go
Introduction to goIntroduction to go
Introduction to goJaehue Jang
 
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 ZikmundKarel 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 184Mahmoud Samir Fayed
 

Ähnlich wie 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
 

Mehr von Oliver N

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 2014Oliver N
 
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 2012Oliver N
 
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...Oliver N
 
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?Oliver N
 
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 CouchbaseOliver N
 
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 ReactOliver N
 
Litibook - Feb 2016
Litibook - Feb 2016Litibook - Feb 2016
Litibook - Feb 2016Oliver N
 
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 GoOliver N
 
Modern Web Development in 2015
Modern Web Development in 2015Modern Web Development in 2015
Modern Web Development in 2015Oliver N
 
Isomorphic web application
Isomorphic web applicationIsomorphic web application
Isomorphic web applicationOliver N
 

Mehr von 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
 

Kürzlich hochgeladen

Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationShrmpro
 
%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 tembisamasabamasaba
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
%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 Hazyviewmasabamasaba
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...masabamasaba
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...Nitya salvi
 
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...masabamasaba
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfayushiqss
 
%+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
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
%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 kaalfonteinmasabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 

Kürzlich hochgeladen (20)

Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions Presentation
 
%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
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
%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
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
%+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...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
%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
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 

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