SlideShare a Scribd company logo
1 of 58
Inner workings of go
channel
me := employeeService.GetByName(“Asad Awadia”)
fmt.Println(me.Does()) // Backend Dev at Textnow
Go developer from 9-5
Kotlin developer from 5-9
Share memory by communicating
Don’t communicate by sharing
memory
But first, quick look at goroutines
Goroutines are lighter weight and
cheaper than regular threads
~4 KB vs ~2MB
Context switching ~10s ns vs 1 us
Channels are a FIFO communication pipe
Pass data to it or read data from it
myChan <- dataIWantToWrite
variableIWantToReadInto := <- myChan
Can also have uni-direction channels
Do I have to close channels?
Are channels expensive?
Mistakes?
Go’s official documentation states that “A common Go newbie mistake is to
over-use channels and goroutines just because it’s possible, and/or
because it’s fun.”
Chan internals
17
18
19
20
Write to a channel?
22
23
24
EZ PZ
What about reads?
EZ PZ
31
32
33
34
35
36
37
Write to a full channel
38
39
40
41
General Algorithm:
1) Setup state for resumption
2) Pause self
42
General Algorithm:
1) Setup state for resumption
2) Pause self
43
44
45
General Algorithm:
1) Setup state for resumption
2) Pause self
46
47
Somebody comes in and reads from the
channel opening a slot
49
50
51
52
Reading from an empty channel
55
56
57
Questions?
Reach out: asad.awadia@textnow.com
Slides influenced by: GopherCon2017 – Kavya Joshi – Understanding Channels

More Related Content

Similar to Inner workings of go channel

Self-Organized Inter-Destination Multimedia Synchronization for Adaptive Medi...
Self-Organized Inter-Destination Multimedia Synchronization for Adaptive Medi...Self-Organized Inter-Destination Multimedia Synchronization for Adaptive Medi...
Self-Organized Inter-Destination Multimedia Synchronization for Adaptive Medi...Benjamin Rainer
 
PPU Optimisation Lesson
PPU Optimisation LessonPPU Optimisation Lesson
PPU Optimisation Lessonslantsixgames
 
Assignment 1-mtat
Assignment 1-mtatAssignment 1-mtat
Assignment 1-mtatzafargilani
 
Efficient logging in multithreaded C++ server
Efficient logging in multithreaded C++ serverEfficient logging in multithreaded C++ server
Efficient logging in multithreaded C++ serverShuo Chen
 
10 reasons to be excited about go
10 reasons to be excited about go10 reasons to be excited about go
10 reasons to be excited about goDvir Volk
 
[ACNA2022] Hadoop Vectored IO_ your data just got faster!.pdf
[ACNA2022] Hadoop Vectored IO_ your data just got faster!.pdf[ACNA2022] Hadoop Vectored IO_ your data just got faster!.pdf
[ACNA2022] Hadoop Vectored IO_ your data just got faster!.pdfMukundThakur22
 
Go Programming language, golang
Go Programming language, golangGo Programming language, golang
Go Programming language, golangBasil N G
 

Similar to Inner workings of go channel (9)

Move from C to Go
Move from C to GoMove from C to Go
Move from C to Go
 
Nug2004 yhe
Nug2004 yheNug2004 yhe
Nug2004 yhe
 
Self-Organized Inter-Destination Multimedia Synchronization for Adaptive Medi...
Self-Organized Inter-Destination Multimedia Synchronization for Adaptive Medi...Self-Organized Inter-Destination Multimedia Synchronization for Adaptive Medi...
Self-Organized Inter-Destination Multimedia Synchronization for Adaptive Medi...
 
PPU Optimisation Lesson
PPU Optimisation LessonPPU Optimisation Lesson
PPU Optimisation Lesson
 
Assignment 1-mtat
Assignment 1-mtatAssignment 1-mtat
Assignment 1-mtat
 
Efficient logging in multithreaded C++ server
Efficient logging in multithreaded C++ serverEfficient logging in multithreaded C++ server
Efficient logging in multithreaded C++ server
 
10 reasons to be excited about go
10 reasons to be excited about go10 reasons to be excited about go
10 reasons to be excited about go
 
[ACNA2022] Hadoop Vectored IO_ your data just got faster!.pdf
[ACNA2022] Hadoop Vectored IO_ your data just got faster!.pdf[ACNA2022] Hadoop Vectored IO_ your data just got faster!.pdf
[ACNA2022] Hadoop Vectored IO_ your data just got faster!.pdf
 
Go Programming language, golang
Go Programming language, golangGo Programming language, golang
Go Programming language, golang
 

Recently uploaded

MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 

Recently uploaded (20)

MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 

Inner workings of go channel

Editor's Notes

  1. Let’s talk about channels
  2. My name is
  3. Let’s get the obligatory share memory by blah blah blah out of the way We have all heard it – waay to many times I would add So let’s just get it over with
  4. They can only transfer data of ONE data type
  5. Before talking about channels – let’s quickly go over goroutines L1 Cache is 0.5 ns L2 cache is 7ns Packet from CA to Netherlands to CA is ~150ms
  6. They can only transfer data of ONE data type
  7. Prints nil Zero value of a channel is nil
  8. Use a make Channels by default are pointers – so if you print you’ll see a memory address Allocates on the heap
  9. Look at the direction of the arrow Write to a channel Read from a channel
  10. Look at the direction of the arrow Write to a channel Read from a channel
  11. Look at the direction of the arrow Write to a channel Read from a channel
  12. You don’t have to They are not file handles Its not the same as a http connection, socket, database or redis or file Its just a way to tell the receivers that the sending is finished The resource will get Gced Writing to a close channel is a panic – your app will crash
  13. Depends If you are doing 2+2 then yeah But if you are doing an expensive blocking call like an http get then no
  14. A lot of go devs get into the language because of goroutines and channels Have an array of URLs – do parallel get requests or downloads Do not over use channels because of the novelty
  15. Let’s look at the chan internals now
  16. When you write this – you get a pointer back
  17. The only things to keep in mind here is the buf which is a circular queue The sendx and receivex which are the indices to that buffer The recvq and sendq which keep track of goroutines which we will see in a bit Waitq is a sudog struct And the lock which is a mutex
  18. This is the actual goroutine struct
  19. And this is the sudog which was the waitq in the channel G is the goroutine and elem is the data which we will see how that works The elem is an unsafe pointer – because you can make channels of any type – so its basically like generics or a void in C
  20. So this is what a channel is
  21. Lets look at how do you write to channel
  22. Copy the data
  23. Release the lock Ez pz
  24. Ez pz
  25. What about reads?
  26. lock
  27. read
  28. Release lock
  29. Ez pz
  30. So lets look at the indices now
  31. When you make a channel this is what gets made – a crcular queue – send and receive indices and a lock
  32. If I do an enque – write to the buffer And update send x to 1
  33. Add two more now full So send x is now 0
  34. When you read from a channel – it does a deque And changes recevx to 1
  35. Two more reads – two more deques So now recevx is back to 0
  36. From the day we are born we are taught that writing to a full channel is a blocking operation Readfing from an empty channel is a blocking operation
  37. So now the buffer is full and we are trying to write to it We know this is a blocking operation – but how does the runtime scheduler do it
  38. Quick break to talk about the go runtime scheduler
  39. So now the buffer is full and we are trying to write to it We know this is a blocking operation – but how does the runtime scheduler do it
  40. This is super useful The goroutine is blocked not the thread - so we are still using resources optimally
  41. Now I need to setup state so that goroutine can be resumed later on somehow
  42. Remember the sudog element from before
  43. Now there is a slot open
  44. Now when some one comes and reads the buffer There is space again The dequee is the read
  45. So we put the elem in the slot that just opened up by popping the sendq
  46. And then set g1 to be ready
  47. And add back to the q to be scheduled later If there were multiple goroutines blocked – since it’s linkedlist/FIFO – the earliest one gets put on first
  48. They can only transfer data of ONE data type
  49. We are trying to receive on an empty channe so it blocks
  50. On the receivng side it’s the opposite We put the sudog struct on the recevq
  51. And now when someone comes to read it we can either write it to the buffer and then read from there Or we can be smarter and use the address of the memory location we have and write it there directly The goroutine will write it into the other goroutine’s stack space directly