How to Use Channels For Communication Between Goroutines In Golang?

9 minutes read

Channels in Go are a powerful feature that enables communication and synchronization between goroutines. They provide a way for goroutines to send and receive values to and from each other, allowing for safe concurrent programming.


To use channels for communication between goroutines in Go, you first need to create a channel using the make function with the chan keyword, specifying the type of values the channel will transmit. For example, to create a channel that transmits integers, you would use:

1
ch := make(chan int)


You can then use the channel to send and receive values. To send a value on a channel, you use the <- operator followed by the channel variable. For example:

1
ch <- 42


To receive a value from a channel, you use the <- operator on the left-hand side, like this:

1
value := <-ch


Note that both sending and receiving operations are blocking by default. This means that if a goroutine tries to send a value on a channel and there is no goroutine waiting to receive it, the sender will be blocked until a receiver is available. Similarly, if a goroutine tries to receive a value from a channel and there is no sender currently sending a value, the receiver will be blocked until a sender is available.


You can also perform non-blocking channel operations using the select statement. The select statement allows you to perform multiple channel operations simultaneously and execute the one that is ready. Here's an example:

1
2
3
4
5
6
7
8
select {
case value := <-ch1:
    // handle received value from ch1
case ch2 <- 42:
    // handle successful send to ch2
default:
    // handle case when none of the channel operations are ready
}


Channels can also be used to synchronize goroutines. For example, you can create a channel that acts as a semaphore to coordinate the execution of multiple goroutines. By sending and receiving values on the channel, you can control when the goroutines should start or continue their execution.


Overall, channels in Go provide a simple and elegant way to communicate and synchronize between goroutines, enabling safe and efficient concurrent programming.

Best Golang Books to Read in 2024

1
Go Programming Language, The (Addison-Wesley Professional Computing Series)

Rating is 5 out of 5

Go Programming Language, The (Addison-Wesley Professional Computing Series)

2
Mastering Go: Create Golang production applications using network libraries, concurrency, machine learning, and advanced data structures, 2nd Edition

Rating is 4.9 out of 5

Mastering Go: Create Golang production applications using network libraries, concurrency, machine learning, and advanced data structures, 2nd Edition

3
Event-Driven Architecture in Golang: Building complex systems with asynchronicity and eventual consistency

Rating is 4.8 out of 5

Event-Driven Architecture in Golang: Building complex systems with asynchronicity and eventual consistency

4
Hands-on Go Programming : Learn Google’s Golang Programming, Data Structures, Error Handling and Concurrency ( English Edition): Learn Google's Golang ... Handling and Concurrency ( English Edition)

Rating is 4.7 out of 5

Hands-on Go Programming : Learn Google’s Golang Programming, Data Structures, Error Handling and Concurrency ( English Edition): Learn Google's Golang ... Handling and Concurrency ( English Edition)

5
Learn Data Structures and Algorithms with Golang: Level up your Go programming skills to develop faster and more efficient code

Rating is 4.6 out of 5

Learn Data Structures and Algorithms with Golang: Level up your Go programming skills to develop faster and more efficient code

6
Hands-On Software Architecture with Golang: Design and architect highly scalable and robust applications using Go

Rating is 4.5 out of 5

Hands-On Software Architecture with Golang: Design and architect highly scalable and robust applications using Go

7
Hands-On Software Engineering with Golang: Move beyond basic programming to design and build reliable software with clean code

Rating is 4.4 out of 5

Hands-On Software Engineering with Golang: Move beyond basic programming to design and build reliable software with clean code


What is a channel direction in Golang?

In Go, a channel direction is a feature that allows you to specify the permitted operations on a channel.


There are three possible channel directions:

  1. Send-only channel: This is denoted by the notation chan<-. It means that the channel can only be used to send values and receiving from it will result in a compile-time error.
  2. Receive-only channel: This is denoted by the notation <-chan. It means that the channel can only be used to receive values and sending to it will result in a compile-time error.
  3. Bidirectional channel: This is denoted by the notation chan. It means that the channel can be used for both sending and receiving values.


By specifying the direction of a channel, you can enforce better code safety and control over how the channel is used. For example, you can prevent accidental writes to a channel that should only be used for receiving, or prevent accidental reads from a channel that should only be used for sending.


How to iterate over values received from a channel using the range keyword in Golang?

To iterate over values received from a channel using the range keyword in Golang, you can follow these steps:

  1. Create a channel by using the make() function. ch := make(chan int)
  2. Start a goroutine to send values to the channel. go func() { ch <- 1 ch <- 2 ch <- 3 close(ch) }()
  3. Iterate over the channel using the range keyword in a separate goroutine. go func() { for v := range ch { // Process each value received from the channel fmt.Println(v) } }()


By using the range keyword with a channel, the loop will exit automatically when the channel is closed.


Here's a complete example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package main

import (
    "fmt"
)

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

    go func() {
        ch <- 1
        ch <- 2
        ch <- 3
        close(ch)
    }()

    go func() {
        for v := range ch {
            fmt.Println(v)
        }
    }()

    // Wait for goroutines to finish
    var input string
    fmt.Scanln(&input)
}


In this example, the values 1, 2, and 3 will be printed by the second goroutine as they are received from the channel.


How to receive data from a channel in Golang?

In Go, you can receive data from a channel using the <- operator. Here's how you can do it:

  1. Create a channel of the desired type:
1
myChannel := make(chan int) // Create a channel of type int


  1. Start a goroutine that sends data to the channel:
1
2
3
4
5
func sendData(channel chan<- int) {
    channel <- 42 // Send some data to the channel
}

go sendData(myChannel) // Start a goroutine to send data to the channel


  1. Receive data from the channel:
1
2
receivedData := <-myChannel // Receive data from the channel
fmt.Println(receivedData) // Print the received data


The <- operator is used to both send and receive data from the channel. When used on the left side of an assignment (<-myChannel), it receives data from the channel. The code will block until data is available on the channel.


Note that the send and receive operations on a channel are blocking by default. This means that if there is no data available to receive, or if there is no receiver available to receive, the code will block until a value is sent or received.

Facebook Twitter LinkedIn Telegram Whatsapp

Related Posts:

Goroutines are a fundamental feature of concurrency in the Go programming language (Golang). They are lightweight, independent units of execution that allow multiple tasks to run concurrently within a single program. Here&#39;s how you can use goroutines for c...
Goroutines are an essential feature of the Go programming language (Golang), which allows concurrent programming. A goroutine is a lightweight, independently executing function or thread managed by the Go runtime. It enables concurrent execution by
To install Golang on your computer, follow these steps:Go to the official Golang website at golang.org.Click on the &#34;Downloads&#34; tab on the website&#39;s navigation menu.Choose the appropriate installer for your operating system (Windows, macOS, or Linu...
When developing web applications using the Go programming language (Golang), creating and handling routes is a fundamental aspect. Routes define the endpoints of the application that users can access to interact with different parts of the system. Here is an o...
Working with databases in Golang involves establishing a connection to the database server, executing queries or database operations, and handling the results. Here are the fundamental steps to work with databases in Golang:Import the necessary packages: To in...
Switching from C# to Go requires a shift in mindset and learning a new programming language. Here are some key aspects to consider:Syntax: The syntax of Go is simpler and more concise compared to C#. Go places emphasis on readability and ease of use. It lacks ...