Home >Backend Development >Golang >Golang determines that chan is closed

Golang determines that chan is closed

WBOY
WBOYOriginal
2023-05-10 15:55:072192browse

When learning and using golang, we often encounter situations where we need to use chan to implement coroutine concurrency. However, in actual use, we sometimes need to determine whether a chan has been closed. This article introduces several Golang methods to determine whether a chan is closed.

First of all, it is very important to understand the basic usage and characteristics of chan in golang. Chan in golang is a concurrency control mechanism based on the CSP model, which can realize communication and synchronization between coroutines. Chan's communication method is blocking. When the read or write operation cannot be completed, the coroutine will be blocked until data can be read or free space can be written. A characteristic of chan is that when chan has been closed, reading and writing operations again will cause panic. Therefore, how to determine whether chan has been closed becomes very important.

The following are several methods for Golang to determine whether chan is closed:

Method 1: Add a signal

We can judge by adding a signal to the chan variable. Whether chan is closed. When chan is closed, we can tell other coroutines that the chan has been closed by closing the signal.

The sample code is as follows:

package main

import "fmt"

func main() {
    a := make(chan int)
    quit := make(chan bool)

    go func() {
        for {
            select {
            case x := <-a:
                fmt.Println(x)
            case <-quit:
                fmt.Println("chan closed")
                return
            }
        }
    }()

    for i := 0; i < 5; i++ {
        a <- i
    }
    close(a)
    quit <- true

    fmt.Println("done")
}

In the above code, we created a chan of type int named a and a chan of type bool named quit. In the coroutine, the read operation of a and the signal closing operation of quit are monitored through select. When chan is closed, the coroutine is informed through the signal of quit. In the main coroutine, we input 5 data to a, then close a through the close() function, and notify the end of the coroutine through the quit signal. Finally, done is printed to indicate that the program execution is complete.

Method 2: Use the range function

We can also use the range function to determine whether chan has been closed. When chan is closed, the range function will end. The following is the sample code:

package main

import "fmt"

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

    go func() {
        for x := range a {
            fmt.Println(x)
        }
        fmt.Println("chan closed")
    }()

    for i := 0; i < 5; i++ {
        a <- i
    }
    close(a)

    fmt.Println("done")
}

In the above code, we first create a chan of type int named a. In the coroutine, the data in chan is traversed through the range function. When chan is closed, the range function will end the coroutine and print "chan closed" to indicate that chan has been closed. In the main coroutine, we input 5 data to a, and then close a through the close() function. Finally, done is printed to indicate that the program execution is complete.

Method 3: Use the ok variable

Another way to determine whether chan has been closed is through the ok variable. When the channel is closed, the ok variable will become false.

The sample code is as follows:

package main

import "fmt"

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

    go func() {
        for {
            x, ok := <-a
            if !ok {
                fmt.Println("chan closed")
                break
            }
            fmt.Println(x)
        }
    }()

    for i := 0; i < 5; i++ {
        a <- i
    }
    close(a)

    fmt.Println("done")
}

In the above code, we create a chan of type int named a. In the coroutine, we traverse the data in chan through the for loop. If the ok variable becomes false, it means that chan has been closed and the loop ends. Print "chan closed", and then break out of the loop. In the main coroutine, we input 5 data to a, and then close a through the close() function. Finally, done is printed to indicate that the program execution is completed.

The above three methods can all determine whether chan in golang is closed. You can choose the appropriate method according to personal needs. Determining whether chan is closed is an important knowledge point used in golang. I hope it will be helpful to everyone's learning.

The above is the detailed content of Golang determines that chan is closed. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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