- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我正在尝试在 Go 中实现循环停止。我现在拥有的代码的灵感来自这里: how to kill goroutine
但是,我无法让我的代码按预期运行。我的代码来自复杂代码库的简化版本是这样的:
package main
import (
"fmt"
"time"
)
var quit chan struct{}
var send chan int
func quitroutine() {
for {
select {
case cnt := <-send:
fmt.Println(cnt)
if cnt == 5 {
quit <- struct{}{}
}
}
}
}
func runLoop() {
cnt := 0
for {
select {
case <-quit:
fmt.Println("quit!")
default:
fmt.Println("default")
}
fmt.Println("inloop")
time.Sleep(1 * time.Second)
cnt++
send <- cnt
}
}
func main() {
quit = make(chan struct{})
send = make(chan int)
go quitroutine()
runLoop()
fmt.Println("terminated")
}
此代码崩溃:
default
inloop
5
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send]:
main.runLoop()
/tmp/t.go:37 +0x1a6
main.main()
/tmp/t.go:45 +0xa4
goroutine 5 [chan send]:
main.quitroutine()
/tmp/t.go:18 +0x10e
created by main.main
/tmp/t.go:44 +0x9f
exit status 2
问题:
为什么在 cnt
为 5 后它会崩溃? quitroutine
仅在 cnt == 5
时写入 quit
channel ,但不会自行终止。当 runLoop
时,如果它在 quit
channel 上接收到,应该只打印“quit!” (它不会),但不会自行终止。
为什么我没有得到“退出!”输出?我什至可以获得 quit
channel 吗?
这需要如何正确实现
最佳答案
正如 Adrian 所说,您的一个 goroutine 正在尝试发送 quit
,而另一个试图发送 send
.回答您的问题:
当 cnt == 5
quitroutine
开始尝试发送 quit
.因为quit <- struct{}{}
不是 select
在这种情况下,goroutine 将阻塞直到另一个尝试从 quit
读取.另一个 goroutine 同样被困在试图做 send <- cnt
的过程中。 (当 cnt = 6
时)。
你永远不会得到“退出!”输出是因为那个 goroutine 被卡住了试图做 send <-cnt
.
我看到的最简单的解决方案是调整 runLoop()
这样 send <- cnt
是select
中的一个案例.
我会改变 runLoop()
看起来像这样:
func runLoop() {
cnt := 0
for {
select {
case <-quit:
fmt.Println("quit!")
case send <- cnt: // moved stuff here
fmt.Println("inloop")
time.Sleep(1 * time.Second)
cnt++
default:
fmt.Println("default")
}
// stuff used to be here
}
}
这给了我输出(直到我终止程序):
default
inloop
0
inloop
1
inloop
2
inloop
3
inloop
4
inloop
5
quit!
default
inloop
6
inloop
7
这似乎主要是您所追求的。
我还想指出 select
阻止 quitroutine()
是不必要的,因为它只有一种情况。清理它可能会更清楚地表明 goroutine 在尝试发送时卡住了,并且永远不会从 send
中获取输入。 channel 。
关于go - 停止循环的代码不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46103456/
今天有小伙伴给我留言问到,try{...}catch(){...}是什么意思?它用来干什么? 简单的说 他们是用来捕获异常的 下面我们通过一个例子来详细讲解下
我正在努力提高网站的可访问性,但我不知道如何在页脚中标记社交媒体链接列表。这些链接指向我在 facecook、twitter 等上的帐户。我不想用 role="navigation" 标记这些链接,因
说现在是 6 点,我有一个 Timer 并在 10 点安排了一个 TimerTask。之后,System DateTime 被其他服务(例如 ntp)调整为 9 点钟。我仍然希望我的 TimerTas
就目前而言,这个问题不适合我们的问答形式。我们希望答案得到事实、引用资料或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visit the
我就废话不多说了,大家还是直接看代码吧~ ? 1
Maven系列1 1.什么是Maven? Maven是一个项目管理工具,它包含了一个对象模型。一组标准集合,一个依赖管理系统。和用来运行定义在生命周期阶段中插件目标和逻辑。 核心功能 Mav
我是一名优秀的程序员,十分优秀!