Skip to content Skip to sidebar Skip to footer

Use Select When a Function Needs to Read From Two Channels Before Advancing Golang

In Go linguistic communication, a channel is a medium through which a goroutine communicates with another goroutine and this advice is lock-costless. Or in other words, a aqueduct is a technique which allows to let one goroutine to send data to some other goroutine. Past default channel is bidirectional, means the goroutines can send or receive information through the same channel as shown in the below image:

Creating a Channel

In Go language, a channel is created using chan keyword and it tin can only transfer information of the aforementioned type, different types of information are not immune to transport from the aforementioned channel.

Syntax:

var Channel_name chan Type

You can also create a channel using make() function using a shorthand declaration.

Syntax:

channel_name:= make(chan Blazon)

Example:

package master

import "fmt"

func main() {

var mychannel chan int

fmt.Println( "Value of the channel: " , mychannel)

fmt.Printf( "Blazon of the channel: %T " , mychannel)

mychannel1 := make(chan int )

fmt.Println( "\nValue of the channel1: " , mychannel1)

fmt.Printf( "Type of the channel1: %T " , mychannel1)

}

Output:

Value of the aqueduct:                      Type of the channel: chan int  Value of the channel1:  0x432080 Type of the channel1: chan int                  

Ship and Receive Data From a Channel

In Go language, channel work with two principal operations one is sending and some other 1 is receiving, both the operations collectively known as advice. And the management of <- operator indicates whether the data is received or send. In the channel, the transport and receive operation block until another side is not ready by default. Information technology allows goroutine to synchronize with each other without explicit locks or condition variables.

  1. Transport operation: The send operation is used to send information from i goroutine to some other goroutine with the help of a channel. Values like int, float64, and bool can safety and easy to send through a channel because they are copied so there is no adventure of accidental concurrent admission of the same value. Similarly, strings are as well safe to transfer because they are immutable. Just for sending pointers or reference like a slice, map, etc. through a channel are non safe because the value of pointers or reference may change by sending goroutine or by the receiving goroutine at the same fourth dimension and the consequence is unpredicted. Then, when you utilise pointers or references in the channel you lot must make sure that they can only admission by the i goroutine at a time.
    Mychannel <- element

    The above argument indicates that the data(element) send to the channel(Mychannel) with the help of a <- operator.

  2. Receive performance: The receive functioning is used to receive the data sent by the send operator.
    element := <-Mychannel

    The above statement indicates that the element receives data from the channel(Mychannel). If the consequence of the received statement is not going to use is also a valid argument. You tin can too write a receive argument as:

    <-Mychannel

Example:

package principal

import "fmt"

func myfunc(ch chan int ) {

fmt.Println(234 + <-ch)

}

func main() {

fmt.Println( "start Main method" )

ch := make(chan int )

go myfunc(ch)

ch <- 23

fmt.Println( "End Principal method" )

}

Output:

first Main method 257 End Master method        

Closing a Channel

You can too shut a aqueduct with the help of close() office. This is an in-built part and sets a flag which indicates that no more value volition transport to this channel.

Syntax:

close()

You lot can also shut the channel using for range loop. Here, the receiver goroutine can check the channel is open up or close with the assistance of the given syntax:

ele, ok:= <- Mychannel

Hither, if the value of ok is true which means the channel is open up so, read operations tin be performed. And if the value of is false which means the aqueduct is closed and then, read operations are not going to perform.

Instance:

package principal

import "fmt"

func myfun(mychnl chan string) {

for v := 0; v < 4; v++ {

mychnl <- "GeeksforGeeks"

}

shut(mychnl)

}

func main() {

c := make(chan cord)

become myfun(c)

for {

res, ok := <-c

if ok == faux {

fmt.Println( "Aqueduct Close " , ok)

break

}

fmt.Println( "Channel Open up " , res, ok)

}

}

Output:

Aqueduct Open  GeeksforGeeks truthful Channel Open up  GeeksforGeeks true Channel Open  GeeksforGeeks true Channel Open  GeeksforGeeks truthful Channel Shut  false        

Of import Points

  • Blocking Send and Receive: In the channel when the information sent to a channel the control is blocked in that send statement until other goroutine reads from that channel. Similarly, when a channel receives data from the goroutine the read statement cake until another goroutine argument.
  • Zero Value Channel: The zip value of the channel is nil.
  • For loop in Aqueduct: A for loop can iterate over the sequential values sent on the channel until it closed.

    Syntax:

    for particular := range Chnl {       // statements.. }            

    Example:

    bundle main

    import "fmt"

    func primary() {

    mychnl := brand(chan string)

    go func() {

    mychnl <- "GFG"

    mychnl <- "gfg"

    mychnl <- "Geeks"

    mychnl <- "GeeksforGeeks"

    close(mychnl)

    }()

    for res := range mychnl {

    fmt.Println(res)

    }

    }

    Output:

    GFG gfg Geeks GeeksforGeeks            
  • Length of the Aqueduct: In channel, you can notice the length of the channel using len() role. Here, the length indicates the number of value queued in the channel buffer.

    Example:

    package chief

    import "fmt"

    a

    func main() {

    mychnl := brand(chan string, 4)

    mychnl <- "GFG"

    mychnl <- "gfg"

    mychnl <- "Geeks"

    mychnl <- "GeeksforGeeks"

    fmt.Println( "Length of the channel is: " , len(mychnl))

    }

    Output:

    Length of the channel is:  4
  • Capacity of the Channel: In channel, you can find the chapters of the channel using cap() function. Here, the capacity indicates the size of the buffer.

    Case:

    package primary

    import "fmt"

    func main() {

    mychnl := make(chan cord, five)

    mychnl <- "GFG"

    mychnl <- "gfg"

    mychnl <- "Geeks"

    mychnl <- "GeeksforGeeks"

    fmt.Println( "Capacity of the aqueduct is: " , cap(mychnl))

    }

    Output:

    Chapters of the channel is:  five
  • Select and instance statement in Channel: In go language, select statement is just similar a switch statement without any input parameter. This select statement is used in the channel to perform a unmarried operation out of multiple operations provided by the example block.

taylorfamente.blogspot.com

Source: https://www.geeksforgeeks.org/channel-in-golang/

Postar um comentário for "Use Select When a Function Needs to Read From Two Channels Before Advancing Golang"