goLang Learning Blocks ~ Unbuffered Channels

in #devdlearningblogs6 years ago (edited)

Channel

Channel in Go provides a connection between two goroutines, allowing them to communicate and synchronize the exchange of any resource that is passed through it.

It is the channel’s ability to control the goroutines interaction that creates the synchronization mechanism.

When a channel is created with no capacity, it is called an unbuffered channel. In turn, a channel created with capacity is called a buffered channel.


chan T                       // can be used to send and receive values of type T
chan <- float64             // can only be used to send float64s
<-chan int                 // can only be used to receive ints

Unbuffered channels

Unbuffered channels have no capacity and therefore require both goroutines to be ready to make any exchange.

When a goroutine attempts to send a resource to an unbuffered channel and there is no goroutine waiting to receive the resource, the channel will lock the sending goroutine and make it wait.

When a goroutine attempts to receive from an unbuffered channel, and there is no goroutine waiting to send a resource, the channel will lock the receiving goroutine and make it wait. Synchronization is inherent in the interaction between the send and the receive. One can not happen without the other.

Example


package main

import "fmt"

func main() {
    c := make(chan int)

    // c <- 40               // This code alone will not work as channel blocks without synchronization 

    go func() {              // This is sender, sync is done using goroutine
        c <- 40
    }()

    fmt.Print(<-c)           // Receiver - This is main go routine
}
Sort:  

Congratulations! This post has been upvoted from the communal account, @minnowsupport, by DevD from the Minnow Support Project. It's a witness project run by aggroed, ausbitbank, teamsteem, someguy123, neoxian, followbtcnews, and netuoso. The goal is to help Steemit grow by supporting Minnows. Please find us at the Peace, Abundance, and Liberty Network (PALnet) Discord Channel. It's a completely public and open space to all members of the Steemit community who voluntarily choose to be there.

If you would like to delegate to the Minnow Support Project you can do so by clicking on the following links: 50SP, 100SP, 250SP, 500SP, 1000SP, 5000SP.
Be sure to leave at least 50SP undelegated on your account.

Coin Marketplace

STEEM 0.21
TRX 0.20
JST 0.034
BTC 98833.06
ETH 3391.57
USDT 1.00
SBD 3.08