Go Channel(queue)
Go channel is a Thread-Safe Ring Buffer(similar to Pipe in C, Mpsc in
Rust) for passing messages between goroutines
NOTE: Channels are not needed if 2 or more goroutines are not
present. Channels are designed exclusively for inter-goroutine
communication and synchronization
Data flows in the direction of the arrow < between go routines
close(): is mandatory to call once producer finishes sending data
on channel. if close is not called consumer will keep on waiting and get
deadlocked
channel is just a pointer to hchan structure
struct sudog |
|
|
Types of Channels
Unbuffered, Buffered
Unbuffered ch := make(chan int) |
Buffered ch := make(chan int, 2) |
|
|---|---|---|
| Meaning |
Channel created with 0 size, that means
|
Channel created with size=2, that means
|
| Writing to channel |
Since no buf is present, channel cannot hold any messages When sender writes on channel ch <- 42 and no one is
recieving, it blocks until reciever reads the message.Sender goroutine sits in sendq -> struct sudog -> g struct
|
When 2 ints are written and noone read then sender will block until reciever does not read them |
| Can Deadlock |
Yes. Easier in unbuffered. Conditions for deadlock: 1. Sender goroutine sent data on channel and reciever goroutine is not present to read from it
2. Receiving without a concurrent sender. reading from channel where no writer
|
Yes Conditions for deadlock: 1. Overfilling the buffer: Sending more items than the buffer's capacity without anyone reading them
2. Reading from an empty buffer: Trying to read from an empty buffered channel when no other goroutines are alive to write to it. |
2. Bidirectional / Directional
Directional vs. Undirectional is completely different from
Buffered vs. Unbuffered.
Buffered/Unbuffered defines how the channel behaves internally
(capacity/blocking rules).
Directional/Bidirectional defines who is allowed to read or write to it
(type safety).
By default, all channels you create are bidirectional (you can read and
write). However, you can restrict them in function signatures to prevent
bugs (e.g., preventing a function that should only read from
accidentally writing).
Bidirectional
The unbuffered and buffered channels above are bidirectional ie allows flow in both directions
Directional Channels
1. Write-Only Channel: chan<- int. Look at where the arrow is
pointing. It points into the chan. You are taking an integer (int) and
pushing it into the channel (chan). You are writing(send) data to chan.
ch <- 10.
2. Read-Only Channel: <-chan int. Look at where the arrow is
pointing now. It points away from the chan. Data is flowing out of the
channel (chan). You can only read (receive) data from it. val := <-ch
| Write Only (chan <- int) | Read Only (<-chan int) | |
|---|---|---|
| What | Reads not allowed on channel | Writes not allowed on channel |
| Code |
|
|
WaitGroup (Same as .join() in C++)
waitgroup is a struct which is used for waiting on goroutines, it make
sure main does not exit early while there are go routines which are
doing the work
Similar to Reference Counter whose value is
incremented/decremented based on number of active goroutines
|
|
Code (channel & waitgroup)
|
Code: MultiProducer MultiConsumer using Bounded Queue |
() after lambda
This is used for calling the lambda function
() After LAMBDA
func main() {
func() {
fmt.Println("Hi")
}()
}
$ go run
Hi
func main() {
func() {
fmt.Println("Hi")
}
}
$ go run
func() {…} (value of type func()) is not used
wait on multiple channels. select
package main
import "fmt"
func main() {
ch1 := make(chan int) // Two unbuffered integer channels, ch1 and ch2, are created.
ch2 := make(chan int)
go func() { // Producer Goroutine
ch1 <- 1 // It sends the value 1 into ch1 and 2 into ch2
ch2 <- 2
// 1. Must close channels when finished sending
close(ch1) // explicitly closes both channels to signal to the receiver that no more values will be sent
close(ch2)
}()
for {
select { // Consumer Loop
case v1, ok := <-ch1: // checks whether the channel is still open
if ok {
fmt.Println("ch1:", v1)
} else {
ch1 = nil // 2. Setting a channel to nil disables this case in a select block
}
case v2, ok := <-ch2:
if ok {
fmt.Println("ch2:", v2)
} else {
ch2 = nil
}
}
// 3. If both channels are nil, break out of the infinite loop safely
if ch1 == nil && ch2 == nil {
break
}
}
fmt.Println("Done!")
}
$ go run
ch1: 1
ch2: 2
Done!
Why Channels are Fast
-
1. Direct Copying: If a sender is waiting and a receiver arrives, the Go
runtime copies the data directly from the sender's stack to the
receiver's stack, skipping the channel buffer entirely
2. No busy-waiting: Instead of "busy-waiting" (spinning), a blocked goroutine is "parked" by the Go scheduler.