SlideShare a Scribd company logo
Golang
Channels
Joris Bonnefoy
DevOps @ OVH
Introduction
“Channels are a typed conduit through
which you can send and receive values”
package main
func main() {
ch := make(chan bool)
go func() {
ch <- true
}()
<-ch
close(ch)
}
g(main) g()
true
“Share memory by communicating”
Some specificities...
Channels are typed
package main
func main() {
ch := make(chan bool)
}
Channels can have directions
package main
func main() {
ch := make(chan bool)
callMe(ch, ch)
}
func callMe(recv <-chan bool, send chan<- bool) {
...
}
“Two” types of channel
Channels can be synchronous (unbuffered)
package main
func main() {
ch := make(chan bool)
ch <- true // It blocks
}
Channels can be asynchronous (buffered)
package main
func main() {
ch := make(chan bool, 1)
ch <- true // It doesn’t block
ch <- true // It blocks
}
The third type :)
Channels can be asynchronous with zero-sized elements
package main
func main() {
done := make(chan struct{}, 1)
go func() {
// Doing some stuff
done <- struct{}{}
}()
<-done // Wait for goroutine to finish its work
}
Channel structure
hchan structure
qcount
uint
number of elements in the buffer
dataqsiz
uint
buffer queue size
buf
*buffer
(unsafe) pointer to chan buffer
closed
uint32
flag that shows whether the channel closed or not
recvq
*linked list
list of goroutines waiting to receive data from the chan
sendq
*linked list
list of goroutines waiting to send data from the chan
lock
mutex
mutex for concurrent accesses to the chan
we need uint to
make atomic
operations on these
fields
New hchan structure fields
● elemtype and elemsize
● waitq structure
● sendx and recvx indexes
Synchronous channel
package main
func main() {
ch := make(chan bool)
go func() {
ch <- true
}()
<-ch
}
qcount 0
dataqsiz 0
buf nil
recvq nil
sendq nil
qcount 0
dataqsiz 0
buf nil
recvq
sendq nil
g(main)
g()
write directly to
main goroutine stack
block main
goroutine
This is the only place in the go runtime
where a goroutine writes directly to the
stack of another
Asynchronous channel
package main
func main() {
ch := make(chan bool, 1)
ch <- true
go func() {
<-ch
}()
ch <- true
}
qcount 0
dataqsiz 1
buf
recvq nil
sendq
true
nil g(main)
block main
goroutine
g()
read from
buffer
read next data
from main
goroutine
put it into
the buffer
unlock main
goroutine
Select statement
Select statement
select {
case data := <-ch:
// Do something
default:
// Do something else
}
A little bit more about select
● inspired from C select function
○ allow to wait I/O from a set of file descriptors
● non-deterministic
● optimistic
● based on 2 structures
○ hselect, representing the select statement
○ scase, representing a select case
● a select with only a default case, or one case + the default case, is
automatically rewritten by the compiler to a simpler structure
Select statement run (selectgo)
1. evaluate all the involved channels and values
2. permuting the cases slice elements (randomize)
3. ordering elements according to cases hchan address
4. locking all the channels
5. starting to loop…
a. checking if a channel is already waiting, so we can use it immediately (and it’s done)
b. otherwise, enqueuing on all channels (and sleep)
c. waiting for another goroutine to wake us up
d. another goroutine wake us up (done = 1)
e. dequeuing of all the other channels
i. if we were waken up by a channel close operation, return to a.
ii. else, we’re done :)
Close statement
Close statement
package main
func main() {
ch := make(chan bool)
close(ch)
}
Close statement
● Iterate through all the senders and receivers in queues and unlock them
● Receivers receive the default value for the chan type
○ When the buffer is empty
● Senders panic
Downsides
Downsides
● close operation can panic
○ on nil channels
○ on closed channels
● and make senders panic too
○ if they send on a closed channel
“Only the sender should close its
channel”
1 producer - N consumers
producer
consumer
consumer
consumer
channel
close
consumers receive
default value
corresponding to
the channel type
M producers - N consumers
producer
consumer
consumer
consumer
channel
producer
producer
close
send
panic
producer
M producers - N consumers - 1st proposition
producer
consumer
consumer
consumer
channel
producer
producer
channel
channel
recv: 0recv: 3recv: 2 send: 3
M producers - N consumers - 2nd proposition
producer
consumer
consumer
consumer
channel
producer
producer
send: 0ok := val -> ch
if !ok {
panic(“Channel closed”)
}
Thank you
@devatoria
References
● http://stackoverflow.com/questions/19621149/how-are-go-channels-implemented
● https://golang.org/src/runtime/chan.go
● https://docs.google.com/document/d/1yIAYmbvL3JxOKOjuCyon7JhW4cSv1wy5hC0ApeGMV9s/pub
● http://dmitryvorobev.blogspot.fr/2016/08/golang-channels-implementation.html
● https://golang.org/doc/effective_go.html#channels
● http://www.jtolds.com/writing/2016/03/go-channels-are-bad-and-you-should-feel-bad/
● https://github.com/golang/go/issues/14601
● https://golang.org/pkg/unsafe/#Pointer
● https://golang.org/src/runtime/malloc.go?h=newarray#L817
● http://stackoverflow.com/questions/37021194/how-are-golang-select-statements-implemented
● https://github.com/golang/go/blob/master/src/runtime/select.go
● http://www.tapirgames.com/blog/golang-concurrent-select-implementation

More Related Content

What's hot

Sockets and Socket-Buffer
Sockets and Socket-BufferSockets and Socket-Buffer
Sockets and Socket-Buffer
Sourav Punoriyar
 
Choisir entre une API RPC, SOAP, REST, GraphQL? 
Et si le problème était ai...
Choisir entre une API  RPC, SOAP, REST, GraphQL?  
Et si le problème était ai...Choisir entre une API  RPC, SOAP, REST, GraphQL?  
Et si le problème était ai...
Choisir entre une API RPC, SOAP, REST, GraphQL? 
Et si le problème était ai...
François-Guillaume Ribreau
 
Improving app performance with Kotlin Coroutines
Improving app performance with Kotlin CoroutinesImproving app performance with Kotlin Coroutines
Improving app performance with Kotlin Coroutines
Hassan Abid
 
An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...
Claudio Capobianco
 
Anatomy of the loadable kernel module (lkm)
Anatomy of the loadable kernel module (lkm)Anatomy of the loadable kernel module (lkm)
Anatomy of the loadable kernel module (lkm)
Adrian Huang
 
Virtual Machine Constructions for Dummies
Virtual Machine Constructions for DummiesVirtual Machine Constructions for Dummies
Virtual Machine Constructions for Dummies
National Cheng Kung University
 
Introducing BinarySortedMultiMap - A new Flink state primitive to boost your ...
Introducing BinarySortedMultiMap - A new Flink state primitive to boost your ...Introducing BinarySortedMultiMap - A new Flink state primitive to boost your ...
Introducing BinarySortedMultiMap - A new Flink state primitive to boost your ...
Flink Forward
 
Managing Terraform Module Versioning and Dependencies
Managing Terraform Module Versioning and Dependencies Managing Terraform Module Versioning and Dependencies
Managing Terraform Module Versioning and Dependencies
Nebulaworks
 
Linux Locking Mechanisms
Linux Locking MechanismsLinux Locking Mechanisms
Linux Locking Mechanisms
Kernel TLV
 
Golang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageGolang - Overview of Go (golang) Language
Golang - Overview of Go (golang) Language
Aniruddha Chakrabarti
 
BPF - in-kernel virtual machine
BPF - in-kernel virtual machineBPF - in-kernel virtual machine
BPF - in-kernel virtual machine
Alexei Starovoitov
 
Introduction to Go programming language
Introduction to Go programming languageIntroduction to Go programming language
Introduction to Go programming language
Slawomir Dorzak
 
Go. Why it goes
Go. Why it goesGo. Why it goes
Go. Why it goes
Sergey Pichkurov
 
Dynamic Linker
Dynamic LinkerDynamic Linker
Dynamic Linker
Sanjiv Malik
 
Epoll - from the kernel side
Epoll -  from the kernel sideEpoll -  from the kernel side
Epoll - from the kernel side
llj098
 
C++11 concurrency
C++11 concurrencyC++11 concurrency
C++11 concurrencyxu liwei
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
Mario Fusco
 
Percona Live 2012PPT: MySQL Query optimization
Percona Live 2012PPT: MySQL Query optimizationPercona Live 2012PPT: MySQL Query optimization
Percona Live 2012PPT: MySQL Query optimization
mysqlops
 
malloc & vmalloc in Linux
malloc & vmalloc in Linuxmalloc & vmalloc in Linux
malloc & vmalloc in Linux
Adrian Huang
 

What's hot (20)

Sockets and Socket-Buffer
Sockets and Socket-BufferSockets and Socket-Buffer
Sockets and Socket-Buffer
 
Choisir entre une API RPC, SOAP, REST, GraphQL? 
Et si le problème était ai...
Choisir entre une API  RPC, SOAP, REST, GraphQL?  
Et si le problème était ai...Choisir entre une API  RPC, SOAP, REST, GraphQL?  
Et si le problème était ai...
Choisir entre une API RPC, SOAP, REST, GraphQL? 
Et si le problème était ai...
 
Improving app performance with Kotlin Coroutines
Improving app performance with Kotlin CoroutinesImproving app performance with Kotlin Coroutines
Improving app performance with Kotlin Coroutines
 
An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...An introduction to Rust: the modern programming language to develop safe and ...
An introduction to Rust: the modern programming language to develop safe and ...
 
Anatomy of the loadable kernel module (lkm)
Anatomy of the loadable kernel module (lkm)Anatomy of the loadable kernel module (lkm)
Anatomy of the loadable kernel module (lkm)
 
Virtual Machine Constructions for Dummies
Virtual Machine Constructions for DummiesVirtual Machine Constructions for Dummies
Virtual Machine Constructions for Dummies
 
Introducing BinarySortedMultiMap - A new Flink state primitive to boost your ...
Introducing BinarySortedMultiMap - A new Flink state primitive to boost your ...Introducing BinarySortedMultiMap - A new Flink state primitive to boost your ...
Introducing BinarySortedMultiMap - A new Flink state primitive to boost your ...
 
Managing Terraform Module Versioning and Dependencies
Managing Terraform Module Versioning and Dependencies Managing Terraform Module Versioning and Dependencies
Managing Terraform Module Versioning and Dependencies
 
Linux Locking Mechanisms
Linux Locking MechanismsLinux Locking Mechanisms
Linux Locking Mechanisms
 
Golang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageGolang - Overview of Go (golang) Language
Golang - Overview of Go (golang) Language
 
BPF - in-kernel virtual machine
BPF - in-kernel virtual machineBPF - in-kernel virtual machine
BPF - in-kernel virtual machine
 
Introduction to Go programming language
Introduction to Go programming languageIntroduction to Go programming language
Introduction to Go programming language
 
Go. Why it goes
Go. Why it goesGo. Why it goes
Go. Why it goes
 
Dynamic Linker
Dynamic LinkerDynamic Linker
Dynamic Linker
 
Ipc in linux
Ipc in linuxIpc in linux
Ipc in linux
 
Epoll - from the kernel side
Epoll -  from the kernel sideEpoll -  from the kernel side
Epoll - from the kernel side
 
C++11 concurrency
C++11 concurrencyC++11 concurrency
C++11 concurrency
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Percona Live 2012PPT: MySQL Query optimization
Percona Live 2012PPT: MySQL Query optimizationPercona Live 2012PPT: MySQL Query optimization
Percona Live 2012PPT: MySQL Query optimization
 
malloc & vmalloc in Linux
malloc & vmalloc in Linuxmalloc & vmalloc in Linux
malloc & vmalloc in Linux
 

Similar to Golang Channels

Go Lang Tutorial
Go Lang TutorialGo Lang Tutorial
Go Lang Tutorial
Wei-Ning Huang
 
Csp scala wixmeetup2016
Csp scala wixmeetup2016Csp scala wixmeetup2016
Csp scala wixmeetup2016
Ruslan Shevchenko
 
Concurrency in go
Concurrency in goConcurrency in go
Concurrency in go
borderj
 
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
Francesco Casalegno
 
Fundamental concurrent programming
Fundamental concurrent programmingFundamental concurrent programming
Fundamental concurrent programming
Dimas Prawira
 
Go concurrency
Go concurrencyGo concurrency
Go concurrency
siuyin
 
Design patterns with kotlin
Design patterns with kotlinDesign patterns with kotlin
Design patterns with kotlin
Alexey Soshin
 
Coroutines in Kotlin
Coroutines in KotlinCoroutines in Kotlin
Coroutines in Kotlin
Alexey Soshin
 
Go Concurrency Basics
Go Concurrency Basics Go Concurrency Basics
Go Concurrency Basics
ElifTech
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in Golang
Bo-Yi Wu
 
Kotlin Coroutines. Flow is coming
Kotlin Coroutines. Flow is comingKotlin Coroutines. Flow is coming
Kotlin Coroutines. Flow is coming
Kirill Rozov
 
Iteration
IterationIteration
Iteration
Liam Dunphy
 
C++ Language
C++ LanguageC++ Language
C++ Language
Syed Zaid Irshad
 
Python unit 3 and Unit 4
Python unit 3 and Unit 4Python unit 3 and Unit 4
Python unit 3 and Unit 4
Anandh Arumugakan
 
Giorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrencyGiorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrency
Giorgio Zoppi
 
Go Concurrency Patterns
Go Concurrency PatternsGo Concurrency Patterns
Go Concurrency Patterns
ElifTech
 
Design patterns with Kotlin
Design patterns with KotlinDesign patterns with Kotlin
Design patterns with Kotlin
Alexey Soshin
 
2. overview of c#
2. overview of c#2. overview of c#
2. overview of c#
Rohit Rao
 
While-For-loop in python used in college
While-For-loop in python used in collegeWhile-For-loop in python used in college
While-For-loop in python used in college
ssuser7a7cd61
 

Similar to Golang Channels (20)

Go Lang Tutorial
Go Lang TutorialGo Lang Tutorial
Go Lang Tutorial
 
Csp scala wixmeetup2016
Csp scala wixmeetup2016Csp scala wixmeetup2016
Csp scala wixmeetup2016
 
Concurrency in go
Concurrency in goConcurrency in go
Concurrency in go
 
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
 
Fundamental concurrent programming
Fundamental concurrent programmingFundamental concurrent programming
Fundamental concurrent programming
 
Go concurrency
Go concurrencyGo concurrency
Go concurrency
 
Design patterns with kotlin
Design patterns with kotlinDesign patterns with kotlin
Design patterns with kotlin
 
Coroutines in Kotlin
Coroutines in KotlinCoroutines in Kotlin
Coroutines in Kotlin
 
Go Concurrency Basics
Go Concurrency Basics Go Concurrency Basics
Go Concurrency Basics
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in Golang
 
Kotlin Coroutines. Flow is coming
Kotlin Coroutines. Flow is comingKotlin Coroutines. Flow is coming
Kotlin Coroutines. Flow is coming
 
Iteration
IterationIteration
Iteration
 
Os3
Os3Os3
Os3
 
C++ Language
C++ LanguageC++ Language
C++ Language
 
Python unit 3 and Unit 4
Python unit 3 and Unit 4Python unit 3 and Unit 4
Python unit 3 and Unit 4
 
Giorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrencyGiorgio zoppi cpp11concurrency
Giorgio zoppi cpp11concurrency
 
Go Concurrency Patterns
Go Concurrency PatternsGo Concurrency Patterns
Go Concurrency Patterns
 
Design patterns with Kotlin
Design patterns with KotlinDesign patterns with Kotlin
Design patterns with Kotlin
 
2. overview of c#
2. overview of c#2. overview of c#
2. overview of c#
 
While-For-loop in python used in college
While-For-loop in python used in collegeWhile-For-loop in python used in college
While-For-loop in python used in college
 

Recently uploaded

UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.
ViralQR
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
Peter Spielvogel
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 

Recently uploaded (20)

UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 

Golang Channels

  • 4. “Channels are a typed conduit through which you can send and receive values”
  • 5. package main func main() { ch := make(chan bool) go func() { ch <- true }() <-ch close(ch) } g(main) g() true
  • 6. “Share memory by communicating”
  • 8. Channels are typed package main func main() { ch := make(chan bool) }
  • 9. Channels can have directions package main func main() { ch := make(chan bool) callMe(ch, ch) } func callMe(recv <-chan bool, send chan<- bool) { ... }
  • 11. Channels can be synchronous (unbuffered) package main func main() { ch := make(chan bool) ch <- true // It blocks }
  • 12. Channels can be asynchronous (buffered) package main func main() { ch := make(chan bool, 1) ch <- true // It doesn’t block ch <- true // It blocks }
  • 14. Channels can be asynchronous with zero-sized elements package main func main() { done := make(chan struct{}, 1) go func() { // Doing some stuff done <- struct{}{} }() <-done // Wait for goroutine to finish its work }
  • 16. hchan structure qcount uint number of elements in the buffer dataqsiz uint buffer queue size buf *buffer (unsafe) pointer to chan buffer closed uint32 flag that shows whether the channel closed or not recvq *linked list list of goroutines waiting to receive data from the chan sendq *linked list list of goroutines waiting to send data from the chan lock mutex mutex for concurrent accesses to the chan we need uint to make atomic operations on these fields
  • 17. New hchan structure fields ● elemtype and elemsize ● waitq structure ● sendx and recvx indexes
  • 19. package main func main() { ch := make(chan bool) go func() { ch <- true }() <-ch } qcount 0 dataqsiz 0 buf nil recvq nil sendq nil qcount 0 dataqsiz 0 buf nil recvq sendq nil g(main) g() write directly to main goroutine stack block main goroutine This is the only place in the go runtime where a goroutine writes directly to the stack of another
  • 21. package main func main() { ch := make(chan bool, 1) ch <- true go func() { <-ch }() ch <- true } qcount 0 dataqsiz 1 buf recvq nil sendq true nil g(main) block main goroutine g() read from buffer read next data from main goroutine put it into the buffer unlock main goroutine
  • 23. Select statement select { case data := <-ch: // Do something default: // Do something else }
  • 24. A little bit more about select ● inspired from C select function ○ allow to wait I/O from a set of file descriptors ● non-deterministic ● optimistic ● based on 2 structures ○ hselect, representing the select statement ○ scase, representing a select case ● a select with only a default case, or one case + the default case, is automatically rewritten by the compiler to a simpler structure
  • 25. Select statement run (selectgo) 1. evaluate all the involved channels and values 2. permuting the cases slice elements (randomize) 3. ordering elements according to cases hchan address 4. locking all the channels 5. starting to loop… a. checking if a channel is already waiting, so we can use it immediately (and it’s done) b. otherwise, enqueuing on all channels (and sleep) c. waiting for another goroutine to wake us up d. another goroutine wake us up (done = 1) e. dequeuing of all the other channels i. if we were waken up by a channel close operation, return to a. ii. else, we’re done :)
  • 27. Close statement package main func main() { ch := make(chan bool) close(ch) }
  • 28. Close statement ● Iterate through all the senders and receivers in queues and unlock them ● Receivers receive the default value for the chan type ○ When the buffer is empty ● Senders panic
  • 30. Downsides ● close operation can panic ○ on nil channels ○ on closed channels ● and make senders panic too ○ if they send on a closed channel
  • 31. “Only the sender should close its channel”
  • 32. 1 producer - N consumers producer consumer consumer consumer channel close consumers receive default value corresponding to the channel type
  • 33. M producers - N consumers producer consumer consumer consumer channel producer producer close send panic producer
  • 34. M producers - N consumers - 1st proposition producer consumer consumer consumer channel producer producer channel channel
  • 35. recv: 0recv: 3recv: 2 send: 3 M producers - N consumers - 2nd proposition producer consumer consumer consumer channel producer producer send: 0ok := val -> ch if !ok { panic(“Channel closed”) }
  • 37. References ● http://stackoverflow.com/questions/19621149/how-are-go-channels-implemented ● https://golang.org/src/runtime/chan.go ● https://docs.google.com/document/d/1yIAYmbvL3JxOKOjuCyon7JhW4cSv1wy5hC0ApeGMV9s/pub ● http://dmitryvorobev.blogspot.fr/2016/08/golang-channels-implementation.html ● https://golang.org/doc/effective_go.html#channels ● http://www.jtolds.com/writing/2016/03/go-channels-are-bad-and-you-should-feel-bad/ ● https://github.com/golang/go/issues/14601 ● https://golang.org/pkg/unsafe/#Pointer ● https://golang.org/src/runtime/malloc.go?h=newarray#L817 ● http://stackoverflow.com/questions/37021194/how-are-golang-select-statements-implemented ● https://github.com/golang/go/blob/master/src/runtime/select.go ● http://www.tapirgames.com/blog/golang-concurrent-select-implementation