Concurrency with Go

  • Building concurrency with GoRoutines.
  • Communication between GoRoutines using Channels.
  • Demonstrating Blocking behaviour of UnBuffered Channels in Go.
  • Closing the Channels to handle infinite records in Go.
  • Demonstrating the concurrent approach to fetch data using Channels.
  • Working with Multiple Channels.
  • Unbuffered → When you push a value through an unbuffered channel you’ll get blocked until someone receives on the other hand.
  • Buffered → If you send to the buffer channel until the capacity is filled, you won’t block. Buffered channels are somewhat like bonded queues.
  • In line #9, we create a channel using the make builtin function. This channel is a channel of integers.
  • At line #12, we are trying to receive from the channel and print out here.
  • At line #11, we create a go routine that sends a value to the channel in below snapshot.
  • At line #17, we receive the value from the channel and print out the value.
  • sending zero and receiving zero.
  • sending one, receiving one
  • sending two, and receiving two.
  • At line #19, the sender can signal it is done by closing the channel.
  • At line #22, this time we are going to use the builtin range keyword to iterate over the data being present in this channel, and every time we will print the value we received.
  • At line #9, we’ll create two channels, channel one and channel two. And then we run a routine, that sends a value to channel two.
  • Now we can run a select statement from whatever channels, from where data is expected. In our case, we expect value from channel two, and we print out that we got the value from channel two, and another case, we get the value from channel one, and we print that we got the value from channel one.
  • At line #11, we’re going to make a channel.
  • At line #12, we are creating a routine → That sleeps for 100 milliseconds, and then sends a value on the channel.
  • And then we do a select. One case, we get the value from the output channel, and we print it out.
  • The other channel that a value will be sent on it after 20 milliseconds. And we print out the timeout, if we got the timeout.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
aditya goel

aditya goel

Software Engineer for Big Data distributed systems