20、go 并发

91 阅读2分钟

本文为译文 Introduction to Concurrency

Go is a concurrent language and not a parallel one

并发

Let's consider a person jogging. During his morning jog, let's say his shoelaces become untied. Now the person stops running, ties his shoelaces and then starts running again. This is a classic example of concurrency. The person is capable of handling both running and tying shoelaces, that is the person is able to deal with lots of things at once :)

What is parallelism and how is it different from concurrency

Let's understand it better with the same jogging example. In this case, let's assume that the person is jogging and also listening to music on his iPod. In this case, the person is jogging and listening to music at the same time, that is he is doing lots of things at the same time. This is called parallelism.

Concurrency and Parallelism - A technical point of view

Let's say we are programming a web browser. The web browser has various components. Two of them are the web page rendering area and the downloader for downloading files from the internet. Let's assume that we have structured our browser's code in such a way that each of these components can be executed independently (This is done using threads in languages such as Java and in Go we can achieve this using Goroutines, more on this later). When this browser is run in a single-core processor, the processor will context switch between the two components of the browser. It might be downloading a file for some time and then it might switch to render the html of a user requested web page. This is known as concurrency. Concurrent processes start at different points of time and their execution cycles overlap. In this case, the downloading and the rendering start at different points in time and their executions overlap.

Let's say the same browser is running on a multi-core processor. In this case, the file downloading component and the HTML rendering component might run simultaneously in different cores. This is known as parallelism.

并行程序也不是永远都会比并发的程序跑得快。这是因为运行的组件之间可能需要做通信。例如我们上面浏览器的例子,下载完成后需要通知给用户说下载完成了,渲染区应该弹出一个弹框告诉用户。如果这个通信发生在并发系统中,代价就很低。但是如果组件运行在多核并行系统中,代价就很高了。

Support for concurrency in Go

Concurrency is an inherent part of the Go programming language. Concurrency is handled in Go using Goroutines and channels. We will discuss them in detail in the upcoming tutorials.