什么是golang频道用于? [英] What are golang channels used for?

查看:122
本文介绍了什么是golang频道用于?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


$ b

  ch:= make(chan int)
在查看一些golang代码时,我发现了以下内容:

我在一个在线教程中查找了golang Chanels的工作方式:



缓冲频道





这是我为你了解频道而编写的小代码。现在改变例程的顺序并查看输出结果。每次输出可能有所不同。

 包主

导入(
fmt
time


func main(){
messages:= make(chan int)
去func(){
time .sleep(time.Second * 3)
messages < - 1
()
go func(){
time.Sleep(time.Second * 2)
消息< - 2
}()
去func(){
time.Sleep(time.Second * 1)
消息< - 3
}()
去func(){
for i:=范围消息{
fmt.Println(i)
}
}()
去func(){
time.Sleep(time.Second * 1)
messages < - 4
()
去func(){
time.Sleep (time.Second * 1)
消息< - 5
}()
time.Sleep(time.Second * 5)
}

为了便于理解,请访问此博客,其中描述了例程和渠道GUI。



请访问 http://divan.github。 io / posts / go_concurrency_visualize /


When looking through some golang code I found the following:

  ch := make(chan int)

I looked up in a online tutorial how golang Chanels work:

https://tour.golang.org/concurrency/2

But I find this example unclear.

Can someone give me a easy explanation and an example of the use of channels?

解决方案

chan is a channel in Golang. In simple word you can think it as a box in which you put a item at one end and then pick it from other end.(order does not matter) Something like

Unbuffered Channels

Buffered Channel

This is the small code I have written for you to understand channels. Now change order of go routines and see the outputs. Each time output may differ.

    package main

    import (
        "fmt"
        "time"
    )

    func main() {
        messages := make(chan int)
        go func() {
            time.Sleep(time.Second * 3)
            messages <- 1
        }()
        go func() {
            time.Sleep(time.Second * 2)
            messages <- 2
        }() 
        go func() {
            time.Sleep(time.Second * 1)
            messages <- 3
        }()
        go func() {
            for i := range messages {
                fmt.Println(i)
            }
        }()
        go func() {
            time.Sleep(time.Second * 1)
            messages <- 4
        }()
        go func() {
            time.Sleep(time.Second * 1)
            messages <- 5
        }()
        time.Sleep(time.Second * 5)
    }

For best understanding visit this blog where go routines and channels are described in GUI.

Visit http://divan.github.io/posts/go_concurrency_visualize/

这篇关于什么是golang频道用于?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆