8

GO的第四天学习-Channel

 3 years ago
source link: https://studygolang.com/articles/32030
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

如果说goroutine是go语言程序的并发体的话,那么channel则是他们之间通信机制。一个channel是一个通信机制,他可以让一个goroutine通过它给另一个goroutine发送值信息。每个channel都有一个特殊的类型,也就是channels可以发送数据类型。一个可以发送int类型数据的channel一般写为 chan int。

使用内置函数 make,来创建 channel

ch := make(chan int)

和map类似,channel也对应一个make创建的底层数据结构的引用。当我们复制一个channel或用于函数参数传递时,我们只是拷贝一个channel引用,因此调用者和被调用者都引用同一个channel。和其他的引用类型一样,channel的零值也是nil

ch<-x
x = <-ch
<-ch
close(ch)
ch = make(chan int,3)

不带缓存的 channels

一个基于无缓存channels的发送操作将导致发送者goroutine阻塞。直到另一个goroutine在相同的channel上继续执行操作接收,当发送的值通过channels成功传输之后,两个goroutine可以继续执行后面的语句、反之,如果接收操作发生,那么接收者goroutine也将阻塞,知道有另一个goroutine在相同的channels上执行发送操作。

串联的Channels(pipelone)

channel也可以用于将多个goroutine链接在一起,一个channel的输出作为下一个channel的输入。这种串联的channel就是所谓的通道

package main 

import (
    "fmt"
)

func main() {
    func main() {
    naturals := make(chan int)
    squares := make(chan int)

    // Counter
    go func() {
        for x := 0; x < 100; x++ {
            naturals <- x
        }
        close(naturals)
    }()

    // Squarer
    go func() {
        for x := range naturals {
            squares <- x * x
        }
        close(squares)
    }()

    // Printer (in main goroutine)
    for x := range squares {
        fmt.Println(x)
    }
}
}

有疑问加站长微信联系(非本文作者)

eUjI7rn.png!mobile

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK