SoFunction
Updated on 2025-03-02

Guide to using channel chan in Go language

The Go language channel (chan) is one of the core tools for implementing concurrent programming, which provides a simple and efficient way to communicate between goroutines. In this article, we will dive into the usage posture of channels, including basic operations, concurrent processing, and some common usage patterns.

1. The basics of the channel

A channel is a pipeline in Go that uses data transfer between goroutines. The channels can be synchronous or asynchronous, providing a secure concurrent data transmission mechanism.

Create a channel

ch := make(chan int) // Create a channel for passing int type data

Send and receive data

Send data to the channel:

ch <- 42 // Send data to the channel

Receive data from the channel:

value := <-ch // Receive data from the channel

Close the channel

When the channel is closed, the channel no longer accepts new data, but can continue to read the remaining data.

close(ch) // Close the channel

Traversal channel

You can use range to traverse data in a channel until the channel is closed.

for value := range ch {
    (value)
}

2. Concurrent operations

Channels are especially important in concurrent programming because they provide a secure mechanism for data exchange between multiple goroutines.

Example: Multiple goroutines read the same channel

package main

import (
    "fmt"
    "time"
)

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

    for i := 0; i < 3; i++ {
        go func(id int) {
            for msg := range ch {
                ("Goroutine %d received: %d\n", id, msg)
            }
        }(i)
    }

    for i := 0; i < 10; i++ {
        ch <- i
        (100 * )
    }

    close(ch)
    ()
}

3. Select statement

The select statement is used to select one of multiple channels for operation. It is a powerful tool for handling concurrent operations and channel multiplexing.

Basic usage

select {
case msg1 := <-ch1:
    ("Received from ch1:", msg1)
case msg2 := <-ch2:
    ("Received from ch2:", msg2)
}

Use select to implement timeout control

select {
case msg := <-ch:
    ("Received:", msg)
case <-(5 * ):
    ("Timeout")
}

4. Common Patterns

Producer-Consumer Model

The producer-consumer model is a common scenario for concurrent programming using channels. The producer sends the data to the channel, and the consumer receives the data from the channel and processes it.

package main

import (
    "fmt"
    "time"
)

func producer(ch chan<- int) {
    for i := 0; i < 5; i++ {
        ch <- i
        ()
    }
    close(ch)
}

func consumer(ch <-chan int) {
    for msg := range ch {
        ("Received:", msg)
    }
}

func main() {
    ch := make(chan int)
    go producer(ch)
    consumer(ch)
}

Task Scheduling

Use channels and select to implement task scheduling and work queues.

package main

import (
    "fmt"
    "time"
)

func worker(id int, tasks <-chan int) {
    for task := range tasks {
        ("Worker %d processing task %d\n", id, task)
        ()
    }
}

func main() {
    tasks := make(chan int, 10)

    for i := 1; i <= 3; i++ {
        go worker(i, tasks)
    }

    for i := 1; i <= 10; i++ {
        tasks <- i
    }
    close(tasks)

    (5 * )
}

The Go language channel (chan) provides a concise and powerful way to implement concurrent programming. Through the channel, goroutines can safely exchange data, and the non-blocking and multiplexing characteristics of the channel make complex concurrent operations easier to manage. Understanding and correct use of channels is the key to writing efficient and reliable Go programs.

This is the article about the guide to using channel chan in Go. For more related channel chan content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!