This article will give you a preliminary understanding of Goroutine and channel in the Go language. I hope it will be helpful to you!
The implementation of the CSP
concurrency model of the Go language contains two main components: one is Goroutine
and the other ischannel
. This article will introduce their basic usage and precautions.
Goroutine
is the basic execution unit of the Go
application. It is a lightweight user-level thread , the bottom layer is concurrency achieved through coroutine
(coroutine). As we all know, a coroutine is a user thread running in user mode, so Goroutine
is also scheduled when the Go
program is running.
Syntax: go function/method
You can create a ## through go keyword function/method #Goroutine.
import ( "fmt" "time" ) func printGo() { fmt.Println("具名函数") } type G struct { } func (g G) g() { fmt.Println("方法") } func main() { // 基于具名函数创建 goroutine go printGo() // 基于方法创建 goroutine g := G{} go g.g() // 基于匿名函数创建 goroutine go func() { fmt.Println("匿名函数") }() // 基于闭包创建 goroutine i := 0 go func() { i++ fmt.Println("闭包") }() time.Sleep(time.Second) // 避免 main goroutine 结束后,其创建的 goroutine 来不及运行,因此在此休眠 1 秒 }
闭包 具名函数 方法 匿名函数
Goroutine exist, their execution order is not fixed. Therefore, the results will be different every time you print.
go keyword, we can create
goroutine based on the named function / method, also
goroutine can be created based on anonymous functions/closures.
Goroutine exit? Under normal circumstances, as long as the execution of the
Goroutine function ends or the execution returns, it means the exit of
Goroutine. If
Goroutine's function or method has a return value, it will be ignored when
Goroutine exits.
channel plays an important role in the Go concurrency model. It can be used to implement communication between
Goroutine, and can also be used to implement synchronization between
Goroutine.
#channel is a composite data type. When declaring, you need to specify the elements in
channel type.
Declaration syntax: var ch chan stringDeclare a
channel whose element type is
string through the above code. Only elements of type
string can be stored.
channel is a reference type and must be initialized to write data. It is initialized by
make.
import ( "fmt" ) func main() { var ch chan string ch = make(chan string, 1) // 打印 chan 的地址 fmt.Println(ch) // 向 ch 发送 "Go" 数据 ch <- "Go" // 从 ch 中接收数据 s := <-ch fmt.Println(s) // Go }
ch <- xxx, you can send data to the
channel variable
ch, via
x := <- ch Data can be received from the
channel variable
ch.
channel, an unbuffered # will be created. ##channel
: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;toolbar:false;">ch := make(chan string)</pre><div class="contentsignin">Copy after login</div></div>
The sending and receiving operations of the unbuffered
are synchronous. After the send operation is performed, the corresponding Goroutine
will block. , until there is another Goroutine
to perform the receive operation, and vice versa. What will happen if the send operation and execution operation are placed under the same Goroutine? Take a look at the following code: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;toolbar:false;">import (
"fmt"
)
func main() {
ch := make(chan int)
// 发送数据
ch <- 1 // fatal error: all goroutines are asleep - deadlock!
// 接收数据
n := <-ch
fmt.Println(n)
}</pre><div class="contentsignin">Copy after login</div></div>
After the program is run, you will get
at ch <-
, prompting all Goroutine
In a dormant state, it is deadlocked. To avoid this situation, we need to execute the sending and receiving operations of channel
in different Goroutine
. <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;toolbar:false;">import (
"fmt"
)
func main() {
ch := make(chan int)
go func() {
// 发送数据
ch <- 1
}()
// 接收数据
n := <-ch
fmt.Println(n) // 1
}</pre><div class="contentsignin">Copy after login</div></div>
It can be concluded from the above example: the sending and receiving operations of unbuffered
must be carried out in two different Goroutine
, otherwise it will Occurrencedeadlock
image.
is created: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;toolbar:false;">ch := make(chan string, 5)</pre><div class="contentsignin">Copy after login</div></div>
Buffered
and unbuffered chennel
is different. When performing a send operation, as long as the buffer of channel
is not full, Goroutine
will not hang until the buffer is full. channel
Performing a send operation will cause Goroutine
to hang. Code example: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;toolbar:false;">func main() {
ch := make(chan int, 1)
// 发送数据
ch <- 1
ch <- 2 // fatal error: all goroutines are asleep - deadlock!
}</pre><div class="contentsignin">Copy after login</div></div>
##
ch := make(chan int, 1)
The
channel variable is obtained through the above code, and we can perform sending and receiving operations on it. ch := make(<-chan int, 1)
The
channel variable is obtained through the above code, we can only receive it . ch := make(chan<- int, 1)
The
channel variable is obtained through the above code, we can only send it . 通常只发送 channel
类型和只接收 channel
类型,会被用作函数的参数类型或返回值:
func send(ch chan<- int) { ch <- 1 } func recv(ch <-chan int) { <-ch }
通过内置函 close(c chan<- Type)
,可以对 channel
进行关闭。
在发送端关闭 channel
在 channel
关闭之后,将不能对 channel
执行发送操作,否则会发生 panic
,提示 channel
已关闭。
func main() { ch := make(chan int, 5) ch <- 1 close(ch) ch <- 2 // panic: send on closed channel }
管道 channel
之后,依旧可以对 channel
执行接收操作,如果存在缓冲区的情况下,将会读取缓冲区的数据,如果缓冲区为空,则获取到的值为 channel
对应类型的零值。
import "fmt" func main() { ch := make(chan int, 5) ch <- 1 close(ch) fmt.Println(<-ch) // 1 n, ok := <-ch fmt.Println(n) // 0 fmt.Println(ok) // false }
如果通过 for-range 遍历 channel
时,中途关闭 channel
则会导致 for-range
循环结束。
本文首先介绍了 Goroutine
的创建方式以及其退出的时机是什么。
其次介绍了如何创建 channel
类型变量的有缓冲与无缓冲的创建方式。需要注意的是,无缓冲的 channel
发送与接收操作,需要在两个不同的 Goroutine
中执行,否则会发送 error
。
接下来介绍如何定义只发送和只接收的 channel
类型。通常只发送 channel
类型和只接收 channel
类型,会被用作函数的参数类型或返回值。
最后介绍了如何关闭 channel
,以及关闭之后的一些注意事项。
The above is the detailed content of A preliminary exploration of Goroutine and channel in Go language. For more information, please follow other related articles on the PHP Chinese website!