An introduction to using and visualizing channels in Go

原文:https://www.sohamkamani.com/blog/2017/08/24/golang-channels-explained/

-------------------------------------------------------------------------

An introduction to using and visualizing channels in Go ➡️

August 24, 2017

If you’re a beginner getting into Go, its mostly quite easy and straightforward. That is, until you get to channels.

At first, everything about channels seems confusing and unintuitive. The fact that not many other popular programming languages have a similar concept, means that channels is one concept that you have to spend some time learning them, if you’re starting your journey with Go.

At the end of this article, you should have all you need to understand how channels work in Go.

Visualizing Goroutines

To understand channels properly, it is essential to know how to visualize Goroutines first.

Let’s start with a simple Goroutine, that takes a number, multiplies it by two, and prints its value (Run this code):

package main

import (
"fmt"
"time"
) func main() {
n := 3 // We want to run a goroutine to multiply n by 2
go multiplyByTwo(n) // We pause the program so that the `multiplyByTwo` goroutine
// can finish and print the output before the code exits
time.Sleep(time.Second)
} func multiplyByTwo(num int) int {
result := num * 2
fmt.Println(result)
return result
}

We can visualize this program as a set of two blocks: one being the main funciton, and the other being the multiplyByTwo goroutine.

The problems with this implementation (that can also be seen from the diagram), is that these two parts of our code are rather disconnected. As a consequence :

  • We cannot access the result of multiplyByTwo in the main function.
  • We have no way to know when the multiplyByTwo goroutine completes. As a result of this, we have to pause the main function by calling time.Sleep, which is a hacky solution at best.

Example #1 - Adding a channel to our goroutine

Let’s now look at some code that introduces how to make and use a channel in Go (Run this code):

package main

import (
"fmt"
) func main() {
n := 3 // This is where we "make" the channel, which can be used
// to move the `int` datatype
out := make(chan int) // We still run this function as a goroutine, but this time,
// the channel that we made is also provided
go multiplyByTwo(n, out) // Once any output is received on this channel, print it to the console and proceed
fmt.Println(<-out)
} // This function now accepts a channel as its second argument...
func multiplyByTwo(num int, out chan<- int) {
result := num * 2 //... and pipes the result into it
out <- result
}

A channel gives us a way to “connect” the different concurrent parts of our program. In this case, we can represent this connection between our two concurrent blocks of code visually :

Channels can be thought of as “pipes” or “arteries” that connect the different concrrent parts of our code.

Directionality

You can also observe that the connection is directional (that’s why theres an arrow, and not just a line). To explain this, take a look at the type definition of the out argument of the multiplyByTwo function :

out chan<- int
  • The chan<- declaration tells us that you can only put stuff into the channel, but not receive anything from it.
  • The int declaration tells us that the “stuff” you put into the channel can only be of the int datatype.

Although they look like separate parts, chan<- int can be thought of as one datatype, that describes a “send-only” channel of integers.

Similarly, an example of a “receive-only” channel declaration would look like:

out <-chan int

You can also declare a channel without giving directionality, which means it can send or recieve data :

out chan int

This is actually seen when we create the out channel in the main function :

out := make(chan int)

The reason we had to make a bi-directional channel was because we were using it to send data from the multiplyByTwo function and receive that same data in the main function.

Blocking code

Statements that send or receive values from channels are blocking inside their own goroutine.

This means that when we try to print the value received (in the main function) :

fmt.Println(<-out)

The <-out statement will block the code until some data is received on the out channel. It helps to then visualize this by splitting the main block into two parts : the part that runs until its time to wait for the channel to receive data, and the part that is run after.

The second part of main can only be run once data is received through the channel, which is why the green arrow connects to the second part.

The dotted arrow added here is to show that it is the main function that started the multiplyByTwo goroutine.

Example #2 - Two single directional channels

Example #1 can be implemented another way, by using 2 channels : one for sending data to the goroutine, and another for receiving the result (Run this code).

package main

import (
"fmt"
) func main() {
n := 3
in := make(chan int)
out := make(chan int) // We now supply 2 channels to the `multiplyByTwo` function
// One for sending data and one for receiving
go multiplyByTwo(in, out) // We then send it data through the channel and wait for the result
in <- n
fmt.Println(<-out)
} func multiplyByTwo(in <-chan int, out chan<- int) {
// This line is just to illustrate that there is code that is
// executed before we have to wait on the `in` channel
fmt.Println("Initializing goroutine...") // The goroutine does not proceed until data is received on the `in` channel
num := <-in // The rest is unchanged
result := num * 2
out <- result
}

Now, in addition to mainmultiplyByTwo is also divided into 2 parts: the part before and after the point where we wait on the in channel (num := <- in)

Example #3 - Multiple concurrent goroutines

Now consider the case where we want to run multiplyByTwo concurrently 3 times (Run this code) :

package main

import (
"fmt"
) func main() {
out := make(chan int)
in := make(chan int) // Create 3 `multiplyByTwo` goroutines.
go multiplyByTwo(in, out)
go multiplyByTwo(in, out)
go multiplyByTwo(in, out) // Up till this point, none of the created goroutines actually do
// anything, since they are all waiting for the `in` channel to
// receive some data
in <- 1
in <- 2
in <- 3 // Now we wait for each result to come in
fmt.Println(<-out)
fmt.Println(<-out)
fmt.Println(<-out)
} func multiplyByTwo(in <-chan int, out chan<- int) {
fmt.Println("Initializing goroutine...")
num := <-in
result := num * 2
out <- result
}

It is important to note that there is no guarantee as to which goroutine will accept which input, or which goroutine will return an output first. All the main function “knows”, is that it is sending some data into the in channel, and expects some data to be received on the out channel.

This can be slightly harder to visualize, but hang in there!

The multiple concurrent goroutines require a different visualization for channels. Here, we see a channel as a kind of “pool” of data (formally known as a buffer). For the purple channel (in), the main function puts in data, and one of the initialized goroutines receive the data. There is no information regarding which goroutine takes which data. This is the same for the green out channel going back into the main routine.

The main routine is now split into 4 parts, since 3 parts now correspond to the 3 times we have to wait ont he out channel (as described by the 3 fmt.Println(<-out) statements), and another part for the operations before the first fmt.Println(<-out) statement.

The multiplyByTwo goroutines on their own, look (and function) the same as before.

Going forward from here

A lot of the time, programs written in Go are highly confusing because of the concurrency and asynchronous nature of the code. Visualizing your code before you proceed to write it (or for that matter, visualizing someone else’s code before you modify it), can help a great deal and actually save you time in understanding.

All this being said, channels in Go make concurrent programming much easier than it would be without them, and its hard to appreciate the amount of code that we don't have to write because of them. Hopefully, these visualizations make it even easier.

【转】An introduction to using and visualizing channels in Go的更多相关文章

  1. 协程和Goroutines示例

    一. 协程的定义 Coroutines are computer-program components that generalize subroutines for non-preemptive m ...

  2. django channle的使用

    频道在PyPI上可用 - 要安装它,只需运行:   参照:https://channels.readthedocs.io/en/latest/introduction.html pip install ...

  3. RabbitMQ消息队列(一): Detailed Introduction 详细介绍

     http://blog.csdn.net/anzhsoft/article/details/19563091 RabbitMQ消息队列(一): Detailed Introduction 详细介绍 ...

  4. Introduction to Financial Management

    Recently,i am learning some useful things about financial management by reading <Essentials of Co ...

  5. Introduction To Monte Carlo Methods

    Introduction To Monte Carlo Methods I’m going to keep this tutorial light on math, because the goal ...

  6. An Introduction to Stock Market Data Analysis with R (Part 1)

    Around September of 2016 I wrote two articles on using Python for accessing, visualizing, and evalua ...

  7. R TUTORIAL: VISUALIZING MULTIVARIATE RELATIONSHIPS IN LARGE DATASETS

    In two previous blog posts I discussed some techniques for visualizing relationships involving two o ...

  8. Netty Tutorial Part 1: Introduction to Netty [z]

    Netty Tutorial, Part 1: Introduction to Netty Update:  Part 1.5 Has Been Published: Netty Tutorial P ...

  9. 学习笔记之Introduction to Data Visualization with Python | DataCamp

    Introduction to Data Visualization with Python | DataCamp https://www.datacamp.com/courses/introduct ...

随机推荐

  1. Ubuntu16.04 安装搜狗Linux中文输入法

    参考链接: https://blog.csdn.net/leijieZhang/article/details/53707181 补充:安装完搜狗拼音输入法后候选栏是乱码的情况,解决方法如下: 输入如 ...

  2. 多个进程间通信之Queue

    多个进程间通信之Queue 实现数据传递 #!coding:utf-8 from multiprocessing import Process, Queue import os,time,random ...

  3. H5混合开发中android终端和ios终端常见的兼容问题2

    转自 https://www.cnblogs.com/stoneniqiu/p/6077112.html 1.ios键盘挡住输入框. setInterval(function () { if (doc ...

  4. mysql杂项

    取数据库某个表中的所有的字段 select COLUMN_NAME from information_schema.COLUMNS where table_name = 'your_table_nam ...

  5. php HTTP协议

    HTTP协议 超文本传输协议(HTTP,HyperText Transfer Protocol) 最常见B/s架构中,使用,浏览器端与服务器端数据交互协议. 协议:约定好的一套语法规则. 规定:请求数 ...

  6. GAN代码实战

    batch normalization 1.BN算法,一般用在全连接或卷积神经网络中.可以增强整个神经网络的识别准确率以及增强模型训练过程中的收敛能力2.对于两套权重参数,例如(w1:0.01,w2: ...

  7. Charles4.2.8抓包(http+https)

    Charles 和 Fiddler 一样都是http抓包工具. 之前用 Fiddler 抓个别 ios 手机 https 报文时总卡在哪里返不回任何数据,后来怀疑是 Fiddler 问题,就考虑使用  ...

  8. Different Subsets For All Tuples CodeForces - 660E (组合计数)

    大意: 定义$f(a)$表示序列$a$本质不同子序列个数. 给定$n,m$, 求所有长$n$元素范围$[1,m]$的序列的$f$值之和. 显然长度相同的子序列贡献是相同的. 不考虑空串, 假设长$x$ ...

  9. fiddler数据过滤功能

    设置会话过滤的菜单如下图: 1.勾选Use Filters选项表示使用过滤设置,不勾选则不使用 2.Actions:有四个选项 Run Filterset now:立即运行过滤设置: Load Fil ...

  10. Mycat分布式数据库架构解决方案--rule.xml详解

    echo编辑整理,欢迎转载,转载请声明文章来源.欢迎添加echo微信(微信号:t2421499075)交流学习. 百战不败,依不自称常胜,百败不颓,依能奋力前行.--这才是真正的堪称强大!!! 该文件 ...