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

type hchan struct {
	qcount   uint           // total data in the queue
	dataqsiz uint           // size of the circular queue
	buf      unsafe.Pointer // points to an array of dataqsiz elements
	elemsize uint16
	closed   uint32
	timer    *timer // timer feeding this chan
	elemtype *_type // element type
	sendx    uint   // send index
	recvx    uint   // receive index
	recvq    waitq  // list of recv waiters
	sendq    waitq  // list of send waiters
	bubble   *synctestBubble

	// lock protects all fields in hchan, as well as several
	// fields in sudogs blocked on this channel.
	//
	// Do not change another G's status while holding this lock
	// (in particular, do not ready a G), as this can deadlock
	// with stack shrinking.
	lock mutex
}
type waitq struct {   // Doubly Linked List of Blocked goroutines
    first *sudog    // Pointer to struct sudog
    last  *sudog
}
      

struct sudog

┌──────────────────────────────────── Heap ────────────────────────────────────────────┐
  struct hchan(heap channel)
  ┌────────────────────┬──────────────────────────────────────────────────────────┐
  │thread-safety params│ buf=| | | | | | channel=Ring buffer queue of 5 ints      |
  └────────────────────┴──────────────────────────────────────────────────────────┴
└───────────────────────────────────────────────────────────────────────────────────────┘
   /\
   |
|──────Stack───────|─Shared libs─|─Data Segment─|───────Text / Code Segment (Read Only)───|
|  |               |                            | // Channel=Queue of 5 ints              |
| pointer(ch)      |                            | ch := make(chan int, 5);                |
└─────────────────────────────────────────────────────────────────────────────────────────┘

Write on Channel (ch <- 2)
lock (hchan.lock)
  buf[sendx] = 2
  sendx++
  qcount++
unlock ()
                  

Types of Channels

Unbuffered, Buffered

Unbuffered ch := make(chan int) Buffered ch := make(chan int, 2)
Meaning Channel created with 0 size, that means
struct hchan {
  dataqsiz=0
  buf=nil     // no Ring buffer is allocated
}
Channel created with size=2, that means
struct hchan {
  dataqsiz=2
  buf=| | |     // Once 2 items are written sender will block
}
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

package main
func main() {
    ch := make(chan int) 

    v := 1
    // DeadLock Main goroutine blocks forever because nobody is reading.
    ch <- v
}
            

2. Receiving without a concurrent sender. reading from channel where no writer

package main
import "fmt"

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

  // DeadLock Main goroutine blocks forever because nobody is writing.
	v, ok := <-ch    // Read from channel
	if !ok {
		fmt.Println("Closed")
	} else {
		fmt.Println("Received first value:", v)
	}
}
            
Yes
Conditions for deadlock:
1. Overfilling the buffer: Sending more items than the buffer's capacity without anyone reading them

func main() {
    // Capacity = 1
    ch := make(chan int, 1)
    ch <- 10 // Fine, fills the buffer.
    ch <- 20 // Deadlock Buffer is full, main goroutine blocks forever.
}
            

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

package main
func main() {
    // Write only Channel
    ch := make(chan<-int) 

    // reading from WO Channel
    // invalid operation: cannot receive from send-only channel
    v := <-ch
}
          

package main
func main() {
    // Read only Channel
    ch := make(<-chan int) 

    // Writing from RO Channel
    // invalid operation: cannot send to receive-only channel
    ch <- 1
}
          

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


┌──────────────────────────────────── Heap ────────────────────────────────┐
| struct sync.WaitGroup (12 byte)
| ┌────────────────────────┬───────────────────────┬────────────────────┐
| │state: [counter 4 bytes]│ waiter count [4 byte] | semaphote [4 byte] |
| └────────────────────────┴───────────────────────┴────────────────────┴
└──────────────────────────────────────────────────────────────────────────┘
   /\
   |
|──────Stack───────|─Shared libs─|────Data Segment───────|───Text / Code Segment (Read Only)───|
|  |               |                                     | // Create wait group                |
| pointer(wg)      |                                     | var wg sync.WaitGroup               |
└──────────────────────────────────────────────────────────────────────────────────────────────┘
// main need to wait for 5 go routines
wg.Add(5)         |state = 5|

// 1 go routine exited. decrement state by 1
wg.Done()         |state = 4|

// 1 go routine exited. decrement state by 1
wg.Done()         |state = 3|

// wait until any goroutine is pending processing
wg.Wait()         if (state > 0) Donot exit main

Code (channel & waitgroup)

package main

import (
	"fmt"
	"sync"
)

func main() {
  ch := make(chan int, 1)   // Created a channel of size=1, ie buffer of size=1
  ch <- 1                // Write 1 on channel

  var wg sync.WaitGroup
  wg.Add(1)                 // Waitgroup will wait for 1 go routine before main can exit
  go func() {
    // defer will be called when go routine exit
    // wg.Done() decrement waitgroup, stating this go routine has finished its work
    defer wg.Done()
    v, ok := <-ch        // Inside go routine, read from channel
    if !ok {
      fmt.Println("Error")
      return
    } else {
      fmt.Println(v)
    }
  }()

  // Similar to join() wait in main until all goroutines have not called Done()
  wg.Wait()
}
$ go run
1
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.