Home > Backend Development > Golang > golang channel usage

golang channel usage

WBOY
Release: 2023-05-19 10:02:37
Original
474 people have browsed it

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!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template