Home Backend Development Golang golang channel usage

golang channel usage

May 19, 2023 am 10:02 AM

Golang is a modern programming language that is mainly suitable for applications based on cloud computing and big data. The language has features such as efficiency, reliability, and security. One of the most unique features is the channel.

Channels are a very powerful type in the Golang language that allow data to be safely shared between different concurrent programs. This article will delve into the use of channels and show how to use channels in programs to achieve co-processing and synchronization.

Basic concepts

In Golang, a channel is an object used to transfer data between coroutines. Through channels, Golang ensures that data is thread-safe when being read or written. Channels can be declared in the following ways:

var ch chan int           //声明一个通道变量
ch := make(chan int)      //定义通道,并初始化其容量
Copy after login

There are three main types of channels:

1. One-way channel: only supports the sending or receiving of data

2. Two-way Channel: Supports sending and receiving of data

3. Channel with buffer: Channel type with fixed capacity

Using channel

The channel is created using the make function. Creating a channel requires specifying the channel type and channel capacity (if it is a buffered channel). For example, to create a buffered channel with a capacity of 3, you can use the following code:

ch := make(chan int, 3)
Copy after login

The channel has two main operations:

1. Send operation: Data can be sent to another through the channel A coroutine

2. Receive operation: The coroutine can receive data from the channel.

In Golang, the data type of the channel has the same default value as other variables. For channels, this value is "nil". Therefore, before using a channel, it must be initialized using the make function. If the channel is not initialized, a "panic" runtime exception is thrown.

In actual programming, channels can be used in many different scenarios and use cases. Here are some widely used examples:

1. Blocking/non-blocking mode of channels: In Golang, channels can run in blocking and non-blocking modes. In blocking mode, channel receive and send operations wait until the send or receive is complete. In non-blocking mode, they return immediately if the operation cannot be completed.

Using channels for blocking communication in Go:

package main

import "fmt"

func main() {
    ch := make(chan int)
    go func() {
        ch <- 101         //发送数据到通道
    }()
    ret := <- ch          //从通道读取数据
    fmt.Println(ret)
}
Copy after login

In this example, two coroutines communicate by sending and receiving data on the channel. Once the channel is created, pass it as a parameter to the "go" function, which represents the function that will be run in the goroutine.

2. Synchronous and asynchronous operations of coroutines: Channels can also be used for synchronous and asynchronous operations between coroutines. In Golang, using channels to transfer data between coroutines can achieve synchronous and asynchronous operations of coroutines.

The sample code for synchronous operation is as follows:

package main

import (
    "fmt"
    "time"
)

func main() {
    ch := make(chan string)
    go func() {
        time.Sleep(time.Second * 2)
        ch <- "golang"
    }()
    fmt.Println("Waiting for the channel...")
    data := <- ch
    fmt.Println("Got data:", data)
}
Copy after login

In this example, a piece of data will be sent from the coroutine to the channel after 2 seconds. The main process will wait for the channel to complete the send or receive operation before executing subsequent code.

The sample code for asynchronous operation is as follows:

package main 

import (
    "fmt"
    "time"
)

func main() {
    ch := make(chan int, 1)
    go func() {
        for i := 0; i < 5; i++ {
            ch <- i
            fmt.Printf("goroutine #%d puts %d at %v
",i,i, time.Now().Unix())
        }
    }()
    time.Sleep(time.Second * 2)
    for i := 0; i < 5; i++ {
        v := <- ch
        fmt.Printf("main thread gets %d at %v
",v, time.Now().Unix())
    }
}
Copy after login

This code will generate a cached channel and pass it as a parameter to the function across the coroutine. This function writes integers to the channel, from 0 to 4.

In the main process, the code waits for 2 seconds to switch, and then reads data from the channel in the loop. The output shows that the data in the channel accessed by the main thread and the timestamps of cross-coroutine execution are in reverse order.

3. Iteration mode of channel: Channel can be iterated to access all values ​​of the channel.

package main

import "fmt"

func main() {
    ch := make(chan int,4)
    ch <- 34
    ch <- 18
    ch <- 89
    ch <- 56
    close(ch)
    for x := range ch {
        fmt.Println(x)
    }
}
Copy after login

In iteration mode, traverse the values ​​in the channel through the range, and automatically exit the traversal when the channel is closed.

Summary

This article introduces the basic usage of Golang channels and demonstrates how to use channels to achieve collaboration, synchronous and asynchronous operations between coroutines. Through understanding and familiarity with channels, efficient, safe and reliable concurrent programs can be better implemented.

The above is the detailed content of golang channel usage. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the vulnerabilities of Debian OpenSSL What are the vulnerabilities of Debian OpenSSL Apr 02, 2025 am 07:30 AM

OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

How do you use the pprof tool to analyze Go performance? How do you use the pprof tool to analyze Go performance? Mar 21, 2025 pm 06:37 PM

The article explains how to use the pprof tool for analyzing Go performance, including enabling profiling, collecting data, and identifying common bottlenecks like CPU and memory issues.Character count: 159

How do you write unit tests in Go? How do you write unit tests in Go? Mar 21, 2025 pm 06:34 PM

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

How do you specify dependencies in your go.mod file? How do you specify dependencies in your go.mod file? Mar 27, 2025 pm 07:14 PM

The article discusses managing Go module dependencies via go.mod, covering specification, updates, and conflict resolution. It emphasizes best practices like semantic versioning and regular updates.

PostgreSQL monitoring method under Debian PostgreSQL monitoring method under Debian Apr 02, 2025 am 07:27 AM

This article introduces a variety of methods and tools to monitor PostgreSQL databases under the Debian system, helping you to fully grasp database performance monitoring. 1. Use PostgreSQL to build-in monitoring view PostgreSQL itself provides multiple views for monitoring database activities: pg_stat_activity: displays database activities in real time, including connections, queries, transactions and other information. pg_stat_replication: Monitors replication status, especially suitable for stream replication clusters. pg_stat_database: Provides database statistics, such as database size, transaction commit/rollback times and other key indicators. 2. Use log analysis tool pgBadg

See all articles