draj30958 2016-10-03 07:45
浏览 63
已采纳

渠道有什么用?

When looking through some Go code I found the following:

  ch := make(chan int)

I looked up in a online tutorial how Go Channels 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?

  • 写回答

2条回答 默认 最新

  • douliao1911 2016-10-03 12:44
    关注

    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.

    Unbuffered Channels

    enter image description here

    Buffered Channel

    enter image description here

    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/

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写