Concurrency in Go-2(Go Channels)

Concurrency in Go-2(Go Channels)

The channel acts as a pipe by which we send typed values from one Goroutine to another. It guarantees synchronization since only one Goroutine has access to a data item at any given time. The ownership of the data is passed between different Goroutine. Why use channels in golang?

  • Go channels make asynchronous programming easy and fun to use.

  • Channels provide mechanisms for concurrent execution of functions to communicate by sending and receiving values of a specific element type.

Creating a Go channel You only need to define a channel, channel type using the make function and assign that to a variable. Just like any other types like structs, maps and slices, you need to create a channel before you can use it. Syntax

Steps to create a channel in Go Channels may be created using the make function. Each channel can transmit values of a specific type, called its element type. Channel types are written using the chan keyword followed by their element type.

We use to make similar to slice and map to create channels. Channels are of specific data type represented by [value-type] of the value to be shared i.e sent or received a cross goroutine. e.g ch := make(chan int).

Example:

Explanation:- We have created a func TotalValue(array []int, ch chan int) {}that calculates totals of a given array of inputs. using the channel to send and receive values.

Directional channel in Go In Go, channels are bidirectional by default, but these channels can be directional in such a way that they can only send or receive data from goroutines. This is always denoted by the arrow <- the symbol we discussed above

For example on how to create send or receive only channel Sending channel only

Explanation:- ch chan <- int Using the arrow symbol indicates that our channel can only send data of type integer

Receiving channel only ch <- chan int indicates that our channel can only receive data of type integer.

Unspecified channel ch:= make(chan int) this channel is declared without defining direction i.e sending or receiving, thus it can either send or receive data but they are of specific data type. Mostly, they are defined in a function and can be used in any direction user needs.

Go channel use cases In Go, With Go Channels we can achieve asynchronous and concurrency programming. This synchronization technique has a wider range of uses such as async/await patterns and actor models. Below are uses of the channel in Golang

Sending/scheduling Notification In Go, Notification is considered as one of a kind request from a user or sending a response from the server that returns values that are not important. We use a blank struct type struct {} as the element type of notification channel since its size is zero and hence doesn't consume memory.

Example of schedule notification

Explanation: func notification(t time.Duration) <-chan struct{} {} mimics the After function in the time standard package. it accepts time... second, millisecond, minutes, hours, etc and it's combined with time.Sleep(duration) to ensure that the program is not blocked thus it executes concurrently.

Use of range in Go channels In Go, Range is mainly used with a for loop flow control statement to iterate over a channel to retrieve/read values in it. It maintains the FIFO principle used in queues, FIRST IN, FIRST OUT. With range, we can use different types of channels, from unbuffered to buffered.

Example use of range in a channel

Select statement in Go channels In Go, the Select statement is always useful whenever numerous numbers of goroutines are sharing data. Each channel has to complete execution first before the next. Syntax of select statement

Explanation: ere there are three possible cases specified with three different conditions.

  • If the channel ch1 is in ready to be read state, then its value will be read (and then discarded) and the text “Got something” will be printed using fmt.Println.

  • If ch2 is in ready to be read state, then its value will be read and assigned to the variable x before printing the value of x.

  • If ch3 is ready to be sent to, then the value y is sent to it before printing the value of y. Finally, if no cases are ready, the default statements will be executed. If there’s no default, then the select will block until one of its cases is ready, at which point it performs the associated communication and executes the associated statements. If multiple cases are ready, select will execute one at random.

comma ok idiom In Golang, the comma ok idiom is mostly used as a for loop statement which iterates over a map[type]type{} list to retrieve values when key is passed.

The ok is true if there was a key on the map. So there are two forms of map access built into the language and two forms of this statement. I have provided a simpler code below demonstrating the map[string]string{} and use of comma ok idiom.

Fan in and fan out in golang channel In Golang, Fan In and Fan Out, works together to process data from either a single/multiple stream or pipelines into one channel mainly converge and diverging of the task. A good scenario here could be a computer processor which contains several number of tasks to be executed at simultaneously. once job done notification is shared via bus and registries are updated. Fan-In and Fan-Out works the same way. Below is an example:-

context in golang channel In Go, context is found everywhere in a Go program. context the package provides us with context.Context function which allows us to pass "context" across the whole program. We can pass the context provided by any function that calls it and its subroutes call that requires the context as an argument, i.efunc ReadingContext (ctx context.Context) error {}. To use context.Context effectively you need to understand how to use it and when it's needed.

Different aspects of using context in the Go channel

  • Retrieving and storing data in the database

  • Passing timeout or deadline of a certain function execution Sending cancellation signal

Retrieving and storing data in the database

In Go, channels are essential for communication between goroutines. Channels support bidirectional communication i.e sending and receiving values on the same channel. This mechanism enables goroutines to synchronize without experiencing any deadlock.

Concurrency in Go-1 https://www.linkedin.com/pulse/concurrency-go-golang-part-1-neeraj-kumar-3p6rc/?trackingId=fXSegGyzHWHLry35YfUMbQ%3D%3D

Have a good day.

To view or add a comment, sign in

Explore topics