Home > Backend Development > Golang > Is golang chan closed?

Is golang chan closed?

(*-*)浩
Release: 2019-12-13 11:45:24
Original
3114 people have browsed it

Is golang chan closed?

chan is a very important thing in golang, used for goroutine communication, because the golang program will inevitably have multiple goroutines, how to synchronize these goroutines is Very important.

When using chan, there are a few experiences: (Recommended learning: Go )

First of all, it will always be a symbol & lt Reading or writing, such as v,ok := <-c is reading, and c <- v is writing.

Secondly, when reading, if there is no ok, it can also be read. However, if it is closed, it can be read, and there is no assignment; if you want to know whether it is closed, you need to add ok, that is, unless chan is never closed, reading should use v,ok := <-c instead of v := < ;-c way.

Again, you cannot write to the closed chan, so generally when writing, you need to use a signal chan (generally the buffer is 1) to determine whether to write or give up. Use select to determine whether the write is successful. , or it is closing and needs to give up writing.

Finally, if chan has data after closed, ok will still be true, and it will be false until chan has no data.

When a chanel is closed, retrieval will not block, but will return zero value

package main
 
import "fmt"
 
func main() {
    c := make(chan int, 5)
    c <- 123
    close(c)
     
    fmt.Println(<-c)
    fmt.Println(<-c)
}
Copy after login

Output

123
0
Copy after login

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

Related labels:
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