SlideShare a Scribd company logo
1 of 18
Channels Use Cases
Erhan Yakut / @yakuter
GopherCon Turkey / 18-19 December 2021
Programlama Dilleri
Aktif olarak Go ile geliştirme yapmakla
birlikte uzun yıllar PHP backend
developer olarak proje geliştirdim.
İletişim Bilgisi
Eposta : yakuter@gmail.com
Twitter: @yakuter
İş / Görev
Binalyze isimli Enterprise Forensics
yazılım şirketinde Senior Software
Architect olarak çalışmaktayım.
Tecrübe/Bilgi
Yaklaşık 15+ yıldır yazılım geliştirme ile
ilgilenmekte olup, şu anda işletim
sistemleri üzerinde olay sonrası delillerin
toplanması için yazılım geliştirmekteyim.
Erhan YAKUT
(yakuter)
Biyografi
Ben Kimim?
Why do we need channels?
Goroutines need to communicate each other to synchronize or exchange data with
each other. The solution is channels.
What is channel?
Channels are the pipes that connect concurrent
goroutines. You can send values into channels from one
goroutine and receive those values into another
goroutine.
Channels are a typed conduit through which you can
send and receive values with the channel operator, <-.
ch <- v // Send v to channel ch.
v := <-ch // Receive from ch, and assign value to v.
(The data flows in the direction of the arrow.)
Like maps and slices, channels must be created before
use:
ch := make(chan int)
Closing channels
Senders have the ability to close the channel to notify
receivers that no more data will be sent on the channel.
Receivers can use an additional variable while receiving
data from the channel to check whether the channel has
been closed.
v, ok := <- ch
If ok is false it means that we are reading from a closed
channel.
The value read from a closed channel will be the zero
value of the channel's type. For example, if the channel is
an int channel, then the value received from a closed
channel will be 0.
Only the sender should close a channel, never the
receiver. Sending on a closed channel will cause a panic.
Buffered channels and range
It is possible to create a channel with a buffer. Sends to a
buffered channel are blocked only when the buffer is full.
Similarly receives from a buffered channel are blocked
only when the buffer is empty.
Buffered channels can be created by passing an
additional capacity parameter to the make function
which specifies the size of the buffer.
ch := make(chan type, capacity)
The loop for v := range ch receives values from the
channel repeatedly until it is closed.
Worker pool
In computer programming, a worker pool is a software
design pattern for achieving concurrency of execution in
a computer program.
A worker pool maintains multiple threads waiting for
tasks to be allocated for concurrent execution by the
supervising program.
Select usage
The select statement is used to choose from multiple
send/receive channel operations. The select statement
blocks until one of the send/receive operations is ready. If
multiple operations are ready, one of them is chosen at
random.
The syntax is similar to switch except that each of the
case statements will be a channel operation.
Check context with select and ticker
Tickers are for when you want to do something
repeatedly at regular intervals.
Tickers use a similar mechanism to timers: a channel that
is sent values.
In the example, we’ll use the select builtin on the channel
to await the values as they arrive every interval.
Channels for notification
1-to-1 notification
Notifications can be viewed as special requests/responses
in which the responded values are not important.
Generally, we use the blank struct type struct{} as the
element types of the notification channels, for the size of
type struct{} is zero, hence values of struct{} doesn't
consume memory.
Start/stop signal
If we queue up lots of goroutines, we can have them all
start at the same time by closing the signal channel.
Start/stop signal with waitgroup
To wait for multiple goroutines to finish, we can use a
wait group.
This WaitGroup is used to wait for all the goroutines
launched here to finish. Note: if a WaitGroup is explicitly
passed into functions, it should be done by pointer.
Launch several goroutines and increment the WaitGroup
counter for each.
Avoid re-use of the same i value in each goroutine
closure.
https://go.dev/doc/faq#closures_and_goroutines
Scheduled notification
We can use a timer or sleep function to wait for desired
time and then send signal (notification)
Please note, <-time.After(aDuration) will make the
current goroutine enter blocking state, but a
time.Sleep(aDuration) function call will not.
The use of <-time.After(aDuration) is often used in the
timeout mechanism which will be introduced below.
Use channels as mutex locks
Channels are blocking actions. So we can use them as
mutex locks.
There are two manners to use one-capacity buffered
channels as mutex locks.
- Lock through a send, unlock through a receive.
- Lock through a receive, unlock through a send.
The following is a lock-through-send example.
Use channels as multi access mutexes
Buffered channels can be used as multi access mutexes.
If the capacity of a channel is N, then it can be viewed as
a lock which can have most N owners at any time.
Counting semaphores are often used to enforce a
maximum number of concurrent requests.
Is channel closed
An nice useful isClosed function
Resources
https://go.dev/tour/concurrency/2
https://golangbot.com/channels/
https://go101.org/article/channel-use-cases.html
https://medium.com/@trevor4e/learning-gos-concurrency-through-illustrations-8c4aff603b3
Thank You

More Related Content

What's hot

Lennart Regebro What Zope Did Wrong (And What To Do Instead)
Lennart Regebro   What Zope Did Wrong (And What To Do Instead)Lennart Regebro   What Zope Did Wrong (And What To Do Instead)
Lennart Regebro What Zope Did Wrong (And What To Do Instead)Vincenzo Barone
 
Golang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageGolang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageAniruddha Chakrabarti
 
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
 
Internationalizing Ubuntu apps
Internationalizing Ubuntu appsInternationalizing Ubuntu apps
Internationalizing Ubuntu appsDavid Planella
 
Lets Go - An introduction to Google's Go Programming Language
Lets Go - An introduction to Google's Go Programming Language Lets Go - An introduction to Google's Go Programming Language
Lets Go - An introduction to Google's Go Programming Language Ganesh Samarthyam
 
Python Programming Essentials - M2 - Introduction to Python
Python Programming Essentials - M2 - Introduction to PythonPython Programming Essentials - M2 - Introduction to Python
Python Programming Essentials - M2 - Introduction to PythonP3 InfoTech Solutions Pvt. Ltd.
 
Introduction to scripts
Introduction to scriptsIntroduction to scripts
Introduction to scriptssana mateen
 
scriptcs - scripted C#, REPL and script extensibility
scriptcs - scripted C#, REPL and script extensibilityscriptcs - scripted C#, REPL and script extensibility
scriptcs - scripted C#, REPL and script extensibilityFilip W
 
Windows batch scripting
Windows batch scriptingWindows batch scripting
Windows batch scriptingArghodeepPaul
 
A First Look at Google's Go Programming Language
A First Look at Google's Go Programming LanguageA First Look at Google's Go Programming Language
A First Look at Google's Go Programming LanguageGanesh Samarthyam
 
Glance rebol
Glance rebolGlance rebol
Glance rebolcrazyaxe
 
Feedback from an eclipse plugin developer to provide support to large set of ...
Feedback from an eclipse plugin developer to provide support to large set of ...Feedback from an eclipse plugin developer to provide support to large set of ...
Feedback from an eclipse plugin developer to provide support to large set of ...Aurélien Pupier
 
Python Programming Essentials - M3 - Python Installation
Python Programming Essentials - M3 - Python InstallationPython Programming Essentials - M3 - Python Installation
Python Programming Essentials - M3 - Python InstallationP3 InfoTech Solutions Pvt. Ltd.
 
Create a PHP Library the right way
Create a PHP Library the right wayCreate a PHP Library the right way
Create a PHP Library the right wayChristian Varela
 
'BUILDING ANGULAR APPS WITH NX' by Anastasia Necheporenko
'BUILDING ANGULAR APPS WITH NX' by Anastasia Necheporenko'BUILDING ANGULAR APPS WITH NX' by Anastasia Necheporenko
'BUILDING ANGULAR APPS WITH NX' by Anastasia NecheporenkoOdessaJS Conf
 
Introduction to go lang
Introduction to go langIntroduction to go lang
Introduction to go langAmal Mohan N
 

What's hot (20)

Lennart Regebro What Zope Did Wrong (And What To Do Instead)
Lennart Regebro   What Zope Did Wrong (And What To Do Instead)Lennart Regebro   What Zope Did Wrong (And What To Do Instead)
Lennart Regebro What Zope Did Wrong (And What To Do Instead)
 
Golang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageGolang - Overview of Go (golang) Language
Golang - Overview of Go (golang) Language
 
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)
 
Introduction to Go-Lang
Introduction to Go-LangIntroduction to Go-Lang
Introduction to Go-Lang
 
Internationalizing Ubuntu apps
Internationalizing Ubuntu appsInternationalizing Ubuntu apps
Internationalizing Ubuntu apps
 
Lets Go - An introduction to Google's Go Programming Language
Lets Go - An introduction to Google's Go Programming Language Lets Go - An introduction to Google's Go Programming Language
Lets Go - An introduction to Google's Go Programming Language
 
What’s new in CSharp6
What’s new in CSharp6What’s new in CSharp6
What’s new in CSharp6
 
Python Programming Essentials - M2 - Introduction to Python
Python Programming Essentials - M2 - Introduction to PythonPython Programming Essentials - M2 - Introduction to Python
Python Programming Essentials - M2 - Introduction to Python
 
Introduction to scripts
Introduction to scriptsIntroduction to scripts
Introduction to scripts
 
scriptcs - scripted C#, REPL and script extensibility
scriptcs - scripted C#, REPL and script extensibilityscriptcs - scripted C#, REPL and script extensibility
scriptcs - scripted C#, REPL and script extensibility
 
Php7
Php7Php7
Php7
 
Windows script host
Windows script hostWindows script host
Windows script host
 
Windows batch scripting
Windows batch scriptingWindows batch scripting
Windows batch scripting
 
A First Look at Google's Go Programming Language
A First Look at Google's Go Programming LanguageA First Look at Google's Go Programming Language
A First Look at Google's Go Programming Language
 
Glance rebol
Glance rebolGlance rebol
Glance rebol
 
Feedback from an eclipse plugin developer to provide support to large set of ...
Feedback from an eclipse plugin developer to provide support to large set of ...Feedback from an eclipse plugin developer to provide support to large set of ...
Feedback from an eclipse plugin developer to provide support to large set of ...
 
Python Programming Essentials - M3 - Python Installation
Python Programming Essentials - M3 - Python InstallationPython Programming Essentials - M3 - Python Installation
Python Programming Essentials - M3 - Python Installation
 
Create a PHP Library the right way
Create a PHP Library the right wayCreate a PHP Library the right way
Create a PHP Library the right way
 
'BUILDING ANGULAR APPS WITH NX' by Anastasia Necheporenko
'BUILDING ANGULAR APPS WITH NX' by Anastasia Necheporenko'BUILDING ANGULAR APPS WITH NX' by Anastasia Necheporenko
'BUILDING ANGULAR APPS WITH NX' by Anastasia Necheporenko
 
Introduction to go lang
Introduction to go langIntroduction to go lang
Introduction to go lang
 

Similar to Golang Channels use cases

Fundamental concurrent programming
Fundamental concurrent programmingFundamental concurrent programming
Fundamental concurrent programmingDimas Prawira
 
MuleSoft Surat Virtual Meetup#31 - Async API, Process Error, Circuit Breaker ...
MuleSoft Surat Virtual Meetup#31 - Async API, Process Error, Circuit Breaker ...MuleSoft Surat Virtual Meetup#31 - Async API, Process Error, Circuit Breaker ...
MuleSoft Surat Virtual Meetup#31 - Async API, Process Error, Circuit Breaker ...Jitendra Bafna
 
Communication in Python and the C10k problem
Communication in Python and the C10k problemCommunication in Python and the C10k problem
Communication in Python and the C10k problemJose Galarza
 
Password protected diary
Password protected diaryPassword protected diary
Password protected diarySHARDA SHARAN
 
My programming final proj. (1)
My programming final proj. (1)My programming final proj. (1)
My programming final proj. (1)aeden_brines
 
Containerizing HPC and AI applications using E4S and Performance Monitor tool
Containerizing HPC and AI applications using E4S and Performance Monitor toolContainerizing HPC and AI applications using E4S and Performance Monitor tool
Containerizing HPC and AI applications using E4S and Performance Monitor toolGanesan Narayanasamy
 
Switch case and looping new
Switch case and looping newSwitch case and looping new
Switch case and looping newaprilyyy
 
Advanced Stream Processing with Flink and Pulsar - Pulsar Summit NA 2021 Keynote
Advanced Stream Processing with Flink and Pulsar - Pulsar Summit NA 2021 KeynoteAdvanced Stream Processing with Flink and Pulsar - Pulsar Summit NA 2021 Keynote
Advanced Stream Processing with Flink and Pulsar - Pulsar Summit NA 2021 KeynoteStreamNative
 
Training report anish
Training report anishTraining report anish
Training report anishAnish Yadav
 
Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!olracoatalub
 
Python Streaming Pipelines with Beam on Flink
Python Streaming Pipelines with Beam on FlinkPython Streaming Pipelines with Beam on Flink
Python Streaming Pipelines with Beam on FlinkAljoscha Krettek
 
The Art of Message Queues - TEKX
The Art of Message Queues - TEKXThe Art of Message Queues - TEKX
The Art of Message Queues - TEKXMike Willbanks
 
Splunk Conf 2014 - Getting the message
Splunk Conf 2014 - Getting the messageSplunk Conf 2014 - Getting the message
Splunk Conf 2014 - Getting the messageDamien Dallimore
 
Introduction to Go language
Introduction to Go languageIntroduction to Go language
Introduction to Go languageTzar Umang
 

Similar to Golang Channels use cases (20)

Fundamental concurrent programming
Fundamental concurrent programmingFundamental concurrent programming
Fundamental concurrent programming
 
My final requirement
My final requirementMy final requirement
My final requirement
 
MuleSoft Surat Virtual Meetup#31 - Async API, Process Error, Circuit Breaker ...
MuleSoft Surat Virtual Meetup#31 - Async API, Process Error, Circuit Breaker ...MuleSoft Surat Virtual Meetup#31 - Async API, Process Error, Circuit Breaker ...
MuleSoft Surat Virtual Meetup#31 - Async API, Process Error, Circuit Breaker ...
 
Communication in Python and the C10k problem
Communication in Python and the C10k problemCommunication in Python and the C10k problem
Communication in Python and the C10k problem
 
resume
resumeresume
resume
 
Password protected diary
Password protected diaryPassword protected diary
Password protected diary
 
Switch case and looping jam
Switch case and looping jamSwitch case and looping jam
Switch case and looping jam
 
java
javajava
java
 
My programming final proj. (1)
My programming final proj. (1)My programming final proj. (1)
My programming final proj. (1)
 
Containerizing HPC and AI applications using E4S and Performance Monitor tool
Containerizing HPC and AI applications using E4S and Performance Monitor toolContainerizing HPC and AI applications using E4S and Performance Monitor tool
Containerizing HPC and AI applications using E4S and Performance Monitor tool
 
Switch case and looping new
Switch case and looping newSwitch case and looping new
Switch case and looping new
 
Advanced Stream Processing with Flink and Pulsar - Pulsar Summit NA 2021 Keynote
Advanced Stream Processing with Flink and Pulsar - Pulsar Summit NA 2021 KeynoteAdvanced Stream Processing with Flink and Pulsar - Pulsar Summit NA 2021 Keynote
Advanced Stream Processing with Flink and Pulsar - Pulsar Summit NA 2021 Keynote
 
Training report anish
Training report anishTraining report anish
Training report anish
 
Switch case looping
Switch case loopingSwitch case looping
Switch case looping
 
Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!Yeahhhh the final requirement!!!
Yeahhhh the final requirement!!!
 
Python Streaming Pipelines with Beam on Flink
Python Streaming Pipelines with Beam on FlinkPython Streaming Pipelines with Beam on Flink
Python Streaming Pipelines with Beam on Flink
 
The Art of Message Queues - TEKX
The Art of Message Queues - TEKXThe Art of Message Queues - TEKX
The Art of Message Queues - TEKX
 
Splunk Conf 2014 - Getting the message
Splunk Conf 2014 - Getting the messageSplunk Conf 2014 - Getting the message
Splunk Conf 2014 - Getting the message
 
Introduction to Go language
Introduction to Go languageIntroduction to Go language
Introduction to Go language
 
MultiThreading in Python
MultiThreading in PythonMultiThreading in Python
MultiThreading in Python
 

Recently uploaded

Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 

Recently uploaded (20)

Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 

Golang Channels use cases

  • 1. Channels Use Cases Erhan Yakut / @yakuter GopherCon Turkey / 18-19 December 2021
  • 2. Programlama Dilleri Aktif olarak Go ile geliştirme yapmakla birlikte uzun yıllar PHP backend developer olarak proje geliştirdim. İletişim Bilgisi Eposta : yakuter@gmail.com Twitter: @yakuter İş / Görev Binalyze isimli Enterprise Forensics yazılım şirketinde Senior Software Architect olarak çalışmaktayım. Tecrübe/Bilgi Yaklaşık 15+ yıldır yazılım geliştirme ile ilgilenmekte olup, şu anda işletim sistemleri üzerinde olay sonrası delillerin toplanması için yazılım geliştirmekteyim. Erhan YAKUT (yakuter) Biyografi Ben Kimim?
  • 3. Why do we need channels? Goroutines need to communicate each other to synchronize or exchange data with each other. The solution is channels.
  • 4. What is channel? Channels are the pipes that connect concurrent goroutines. You can send values into channels from one goroutine and receive those values into another goroutine. Channels are a typed conduit through which you can send and receive values with the channel operator, <-. ch <- v // Send v to channel ch. v := <-ch // Receive from ch, and assign value to v. (The data flows in the direction of the arrow.) Like maps and slices, channels must be created before use: ch := make(chan int)
  • 5. Closing channels Senders have the ability to close the channel to notify receivers that no more data will be sent on the channel. Receivers can use an additional variable while receiving data from the channel to check whether the channel has been closed. v, ok := <- ch If ok is false it means that we are reading from a closed channel. The value read from a closed channel will be the zero value of the channel's type. For example, if the channel is an int channel, then the value received from a closed channel will be 0. Only the sender should close a channel, never the receiver. Sending on a closed channel will cause a panic.
  • 6. Buffered channels and range It is possible to create a channel with a buffer. Sends to a buffered channel are blocked only when the buffer is full. Similarly receives from a buffered channel are blocked only when the buffer is empty. Buffered channels can be created by passing an additional capacity parameter to the make function which specifies the size of the buffer. ch := make(chan type, capacity) The loop for v := range ch receives values from the channel repeatedly until it is closed.
  • 7. Worker pool In computer programming, a worker pool is a software design pattern for achieving concurrency of execution in a computer program. A worker pool maintains multiple threads waiting for tasks to be allocated for concurrent execution by the supervising program.
  • 8. Select usage The select statement is used to choose from multiple send/receive channel operations. The select statement blocks until one of the send/receive operations is ready. If multiple operations are ready, one of them is chosen at random. The syntax is similar to switch except that each of the case statements will be a channel operation.
  • 9. Check context with select and ticker Tickers are for when you want to do something repeatedly at regular intervals. Tickers use a similar mechanism to timers: a channel that is sent values. In the example, we’ll use the select builtin on the channel to await the values as they arrive every interval.
  • 10. Channels for notification 1-to-1 notification Notifications can be viewed as special requests/responses in which the responded values are not important. Generally, we use the blank struct type struct{} as the element types of the notification channels, for the size of type struct{} is zero, hence values of struct{} doesn't consume memory.
  • 11. Start/stop signal If we queue up lots of goroutines, we can have them all start at the same time by closing the signal channel.
  • 12. Start/stop signal with waitgroup To wait for multiple goroutines to finish, we can use a wait group. This WaitGroup is used to wait for all the goroutines launched here to finish. Note: if a WaitGroup is explicitly passed into functions, it should be done by pointer. Launch several goroutines and increment the WaitGroup counter for each. Avoid re-use of the same i value in each goroutine closure. https://go.dev/doc/faq#closures_and_goroutines
  • 13. Scheduled notification We can use a timer or sleep function to wait for desired time and then send signal (notification) Please note, <-time.After(aDuration) will make the current goroutine enter blocking state, but a time.Sleep(aDuration) function call will not. The use of <-time.After(aDuration) is often used in the timeout mechanism which will be introduced below.
  • 14. Use channels as mutex locks Channels are blocking actions. So we can use them as mutex locks. There are two manners to use one-capacity buffered channels as mutex locks. - Lock through a send, unlock through a receive. - Lock through a receive, unlock through a send. The following is a lock-through-send example.
  • 15. Use channels as multi access mutexes Buffered channels can be used as multi access mutexes. If the capacity of a channel is N, then it can be viewed as a lock which can have most N owners at any time. Counting semaphores are often used to enforce a maximum number of concurrent requests.
  • 16. Is channel closed An nice useful isClosed function