Passing Data from one goroutine to another goroutine using channels.

Gaurav
2 min readOct 27, 2023

Channels are the pipes that connect concurrent goroutines. You can send values into channels from one goroutine and receive those values into another goroutine.

Channels in Golang can be unbuffered or buffered. Unbuffered channels do not have a capacity and will block the sending goroutine until the receiving goroutine is ready to receive the data. Buffered channels have a capacity and will not block the sending goroutine until the channel is full.

Below is an example of a Buffered Channel for Asynchronous operation.

ch := make(chan int, 10)

Below is an example of a UnBuffered Channel for Asynchronous operation.

ch := make(chan int)

Using Channels

Channels can be used to implement a wide range of concurrent patterns in Golang. Some common use cases for channels include −

  • Synchronization − Channels can be used to synchronize the execution of multiple goroutines.
  • Pipelines − Channels can be used to create pipelines of goroutines that process data in sequence.
  • Fan-out/Fan-in − Channels can be used to distribute work across multiple goroutines and then collect the results.

Fig. 1

Let’s understand the below code which is illustrated in Fig. 1



package main

import (
"fmt"
"sync"
)

func generateNumbers(total int, wg *sync.WaitGroup, ch chan int) {
defer wg.Done()

sum := 0
for idx := 1; idx <= total; idx++ {
fmt.Printf("Generating number %d\n", idx)
sum = sum + idx
ch <- sum
}
}

func printNumbers(wg *sync.WaitGroup, ch chan int) {
defer wg.Done()

for idx := 1; idx <= 3; idx++ {
sum := <-ch
fmt.Printf("Printing number %d and Sum is Currently %d\n", idx, sum)
}
}

func main() {
var wg sync.WaitGroup

ch1 := make(chan int)

wg.Add(2)
go printNumbers(&wg, ch1)
go generateNumbers(3, &wg, ch1)

fmt.Println("Waiting for goroutines to finish...")
wg.Wait()
fmt.Println("Done!")
}

Output:

$go run channels.go

Waiting for goroutines to finish…
Generating number 1
Generating number 2
Printing number 1 and Sum is Currently 1
Printing number 2 and Sum is Currently 3
Generating number 3
Printing number 3 and Sum is Currently 6
Done!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Gaurav
Gaurav

No responses yet

Write a response