goLang Learning Blocks ~ Buffered Channels

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.

Buffered channels

Buffered channels have a capacity and therefore can behave a bit differently. When a goroutine attempts to send a resource to a buffered channel and the channel is full, the channel will lock the goroutine and make it wait until a buffer becomes available. If there is room in the channel, the send can take place immediately and the goroutine can move on.

When a goroutine attempts to receive from a buffered channel and the buffered channel is empty, the channel will lock the goroutine and make it wait until a resource has been sent. If the buffer is full or if there is nothing to receive, a buffered channel will behave very much like an unbuffered channel.

Example


package main

import "fmt"

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

    c <- 40            // sender to channel, sync is not required 
    c <- 45
    // c <- 48        this will block the channel

    fmt.Print(<-c, <-c)    // receiver 
}
Sort:  

Hi! I am a robot. I just upvoted you! I found similar content that readers might be interested in:
https://gobyexample.com/channel-synchronization

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.