教程集 www.jiaochengji.com
教程集 >  Golang编程  >  golang教程  >  正文 从Deadlock报错理解Go channel机制(一)

从Deadlock报错理解Go channel机制(一)

发布时间:2021-12-26   编辑:jiaochengji.com
教程集为您提供从Deadlock报错理解Go channel机制(一)等资源,欢迎您收藏本站,我们将为您提供最新的从Deadlock报错理解Go channel机制(一)资源

Go与其他语言不一样,它从语言层面就已经支持并发,不需要我们依托Thread库新建线程。Go中的channel机制使我们不用过多考虑锁和并发安全问题。channel提供了一种goroutine之间数据流传输的方式。

今天我想从一个常见的deadlock error开始,讨论一下channel的特性。

如果运行以下程序:

<pre><code class="lang-go hljs">var ch = make(chan int) func main() { ch <- 1 <-ch // 没有这行代码也会报同样的错误 }</code></code></pre>

terminal会报如下错误:

<pre><code class="lang-go hljs">fatal error: all goroutines are asleep - deadlock!</code></code></pre>

回顾channel(信道)的概念,大致上来说,信道是goroutine之间相互沟通的管道,信道中数据的流通代表着goroutine之间内存的共享。宏观上来讲,信道有点像其他语言中的队列(queue),遵循先进先出的规则。

信道分为无缓冲信道(即unbuffered channel)和有缓冲信道(buffered channel)。对于无缓冲的信道来说,我们默认信道的发消息(send)和收消息(receive)都是阻塞(block)的。换句话来说,无缓冲的信道在收消息和发消息的时候,goroutine都处于<em>挂起</em>状态。除非另一端准备好,否则goroutine无法继续往下执行。

上面的那段程序便是一个明显的错误样例。在main函数执行到ch <- 1的时候main(也是一个goroutine)便已挂起,而并没有其他goroutine负责接收消息,而下面一句 <-ch 永远无法执行,系统便自动判为timeout返回error。<em>这种所有线程或者进程都在等待资源释放的情况,我们便把它称之为死锁。</em>

死锁是一个非常有意思的话题,常见的死锁大致分为以下几类:
i. 只在单一goroutine里操作信道,例子如上。
ii. 串联信道中间一环挂起,举例如下:

<pre><code class="lang-go hljs">var ch1 chan int = make(chan int) var ch2 chan int = make(chan int) func say(s string) { fmt.Println(s) ch1 <- <- ch2 // ch1 等待 ch2流出的数据 } func main() { go say("hello") <- ch1 // 堵塞主线 }</code></code></pre>

ch1等待ch2留出数据,然而ch2并没有发出数据导致goroutine阻塞,解决方案是给ch2喂数据:

<pre><code class="lang-go hljs">func feedCh2(ch chan int) { ch <- 2 }</code></code></pre>

iii. 非缓冲信道不成对出现:

<pre><code class="lang-go hljs">c, quit := make(chan int), make(chan int) go func() { c <- 1 // c通道的数据没有被其他goroutine读取走,堵塞当前goroutine quit <- 0 // quit始终没有办法写入数据 }() <- quit // quit 等待数据的写</code></code></pre>

当然,并非所有不成对出现的非缓冲信道都会报错:

<pre><code class="lang-go hljs">func say(ch chan int) { ch <- 1 } func main() { ch := make(chan int) go say(ch) }</code></code></pre>

有意思的是,虽然say函数挂起等待信道接收消息,但是main goroutine并没有被阻塞,在main函数返回后程序依然可以自动终止。

关于缓冲信道将会在之后的文章中介绍,如有意见还请指教。

Reference: http://blog.csdn.net/kjfcpua/article/details/18265441

-<em>完</em>-


到此这篇关于“从Deadlock报错理解Go channel机制(一)”的文章就介绍到这了,更多文章或继续浏览下面的相关文章,希望大家以后多多支持JQ教程网!

您可能感兴趣的文章:
从Deadlock报错理解Go channel机制(一)
Go并发编程——channel
golang 切片截取 内存泄露_怎么看待Goroutine 泄露
go语言并发编程
go语言管道总结
一文读透GO语言的通道
golang的channel机制
Golang 并发机制
go 语言并发
Go语言基础(3)

[关闭]
~ ~