赞
踩
编程题:3个函数分别打印cat、dog、fish,要求每个函数都要起一个goroutine,按照cat、dog、fish顺序打印在屏幕上100次。
package main import ( "fmt" "sync" ) // 面试题:每个函数起一个goroutine,轮流打印 cat dog fish 各100次 // 3个goroutine, 打印顺序是 cat dog fish cat dog fish ... 依此类推 var wg sync.WaitGroup func main() { chCatOk := make(chan struct{}, 1) chDogOk := make(chan struct{}, 1) chFishOk := make(chan struct{}, 1) wg.Add(3) // 有3个协程,所以加3 go printAnimal("cat", chCatOk, chDogOk) go printAnimal("dog", chDogOk, chFishOk) go printAnimal("fish", chFishOk, chCatOk) // 先通知cat执行 chCatOk <- struct{}{} wg.Wait() fmt.Println("执行结束") } func printAnimal(word string, ch1 <-chan struct{}, ch2 chan<- struct{}) { count := 0 // 退出前标记完成 defer wg.Done() for _ = range ch1 { fmt.Println(word) count++ ch2 <- struct{}{} // 通知协程2你可以执行了 if count == 100 { return } } }
这个代码只用了一个函数,面试时你可以换成三个名字不一样的函数。
思考,可否换成无缓冲区的 channel
不可以,会报fatal error: all goroutines are asleep - deadlock!
package main
import "fmt"
func main() {
pipline := make(chan string)
pipline <- "hello world"
fmt.Println(<-pipline)
}
运行会抛出错误,如下
fatal error: all goroutines are asleep - deadlock!
看起来好像没有什么问题?先往信道中存入数据,再从信道中读取数据。
回顾前面的基础,我们知道使用 make 创建信道的时候,若不传递第二个参数,则你定义的是无缓冲信道,而对于无缓冲信道,在接收者未准备好之前,发送操作是阻塞的.
因此,对于解决此问题有两种方法:
若要程序正常执行,需要保证接收者程序在发送数据到信道前就进行阻塞状态,修改代码如下
package main
import "fmt"
func main() {
pipline := make(chan string)
fmt.Println(<-pipline)
pipline <- "hello world"
}
运行的时候还是报同样的错误。问题出在哪里呢?
原来我们将发送者和接收者写在了同一协程中,虽然保证了接收者代码在发送者之前执行,但是由于前面接收者一直在等待数据 而处于阻塞状态,所以无法执行到后面的发送数据。还是一样造成了死锁。
有了前面的经验,我们将接收者代码写在另一个协程里,并保证在发送者之前执行,就像这样的代码
package main
func hello(pipline chan string) {
<-pipline
}
func main() {
pipline := make(chan string)
go hello(pipline)
pipline <- "hello world"
}
运行之后 ,一切正常。
接收者代码必须在发送者代码之前 执行,这是针对无缓冲信道才有的约束。
既然这样,我们改使用有缓冲信道不就 OK 了吗?
package main
import "fmt"
func main() {
pipline := make(chan string, 1)
pipline <- "hello world"
fmt.Println(<-pipline)
}
运行之后,一切正常。
Go 语言中通道死锁经典错误案例详解
解决fatal error: all goroutines are asleep - deadlock!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。