Go Channel
- Posted on
- Authors
- Name
- ansidev
- @ansidev
My notes about Go channel.
Channels are a typed conduit through which you can send and receive values with the channel operator,
<-.
Channel can only save homogeneous data type. So you must declare the type of the channel you want to create.
chan int // channel only accepts int chan string // channel only accepts string chan bool // channel only accepts boolchan int // channel only accepts int chan string // channel only accepts string chan bool // channel only accepts boolYou need to initialize a channel before using it with
make, otherwise the channel isniland not available to use.// Syntax: {variable_name} := make(chan {type}) ch := make(chan int) // works var ch2 chan int // don't work// Syntax: {variable_name} := make(chan {type}) ch := make(chan int) // works var ch2 chan int // don't workYou need to initialize a channel before using it with
make.ch := make(chan int) // int is type of channel datach := make(chan int) // int is type of channel dataSending/Receiving data using channel:
x := <- ch // read data from channel ch into variable x ch <- y // send y to the channel chx := <- ch // read data from channel ch into variable x ch <- y // send y to the channel chClose a channel:
close(ch)close(ch)Note: You cannot send data to a closed channel.
Type of channels:
unbuffered channel: a channel is created with no capacity.// Syntax: {variable_name} := make(chan {type}) ch := make(chan int) // unbuffered channel// Syntax: {variable_name} := make(chan {type}) ch := make(chan int) // unbuffered channelbuffered channel: a channel is created with capacity.// Syntax: {variable_name} := make(chan {type}, {capacity}) ch := make(chan int, 5) // buffered channel, capacity = 5// Syntax: {variable_name} := make(chan {type}, {capacity}) ch := make(chan int, 5) // buffered channel, capacity = 5
Channel blocking mechanism:
Unbuffered channel
Sending and receiving are blocked until the other side is ready. This allows goroutines to synchronize without explicit locks or condition variables.
ch := make(chan int) // unbuffered channelch := make(chan int) // unbuffered channelBuffered channel
Sending data to a buffered channel are blocked only when the buffer is full.
Receiving data from a buffered channel are blocked only when the buffer is empty.
ch := make(chan int, 5) // buffered channelch := make(chan int, 5) // buffered channel
Deadlock with channel
A deadlock happens when a group of goroutines are waiting for each other and none of them is able to proceed. Examples:
- The data which are sent into a channel cannot be received by any receiver anywhere in your code.
- You try to read data from a channel but there is no data are sent to the channel anywhere in your code.