- ubuntu12.04环境下使用kvm ioctl接口实现最简单的虚拟机
- Ubuntu 通过无线网络安装Ubuntu Server启动系统后连接无线网络的方法
- 在Ubuntu上搭建网桥的方法
- ubuntu 虚拟机上网方式及相关配置详解
CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.
这篇CFSDN的博客文章关于Golang中for-loop与goroutine的问题详解由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.
背景 。
最近在学习MIT的分布式课程6.824的过程中,使用Go实现Raft协议时遇到了一些问题。分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧.
参见如下代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
for
i := 0; i < len(rf.peers); i++ {
DPrintf(
"i = %d"
, i)
if
i == rf.me {
DPrintf(
"skipping myself #%d"
, rf.me)
continue
}
go func() {
DPrintf(
"len of rf.peers = %d"
, len(rf.peers))
DPrintf(
"server #%d sending request vote to server %d"
, rf.me, i)
reply := &RequestVoteReply{}
ok := rf.sendRequestVote(i, args, reply)
if
ok && reply.VoteGranted && reply.Term == rf.currentTerm {
rf.voteCount++
if
rf.voteCount > len(rf.peers)/2 {
rf.winElectionCh <-
true
}
}
}()
}
|
其中,peers切片的长度为3,因此最高下标为2,在非并行编程中代码中的for-loop应该是很直观的,我当时并没有意识到有什么问题。可是在调试过程中,一直在报 index out of bounds 错误。调试信息显示i的值为3,当时就一直想不明白循环条件明明是 i < 2,怎么会变成3呢.
分析 。
虽然不明白发生了什么,但知道应该是循环中引入的 goroutine 导致的。经过Google,发现Go的wiki中就有一个页面 Common Mistake - Using goroutines on loop iterator variables 专门提到了这个问题,看来真的是很 common 啊,笑哭~ 。
初学者经常会使用如下代码来并行处理数据:
1
2
3
|
for
val := range values {
go val.MyMethod()
}
|
或者使用闭包(closure):
1
2
3
4
5
|
for
val := range values {
go func() {
fmt.Println(val)
}()
}
|
这里的问题在于 val 实际上是一个遍历了切片中所有数据的单一变量。由于闭包只是绑定到这个 val 变量上,因此极有可能上面的代码的运行结果是所有 goroutine 都输出了切片的最后一个元素。这是因为很有可能当 for-loop 执行完之后 goroutine 才开始执行,这个时候 val 的值指向切片中最后一个元素.
1
|
The val variable in the above loops is actually a single variable that takes on the value of each slice element. Because the closures are all only bound to that one variable, there is a very good chance that when you run this code you will see the last element printed for every iteration instead of each value in sequence, because the goroutines will probably not begin executing until after the loop.
|
解决方法 。
以上代码正确的写法为:
1
2
3
4
5
|
for
val := range values {
go func(val interface{}) {
fmt.Println(val)
}(val)
}
|
在这里将 val 作为一个参数传入 goroutine 中,每个 val 都会被独立计算并保存到 goroutine 的栈中,从而得到预期的结果.
另一种方法是在循环内定义新的变量,由于在循环内定义的变量在循环遍历的过程中是不共享的,因此也可以达到同样的效果:
1
2
3
4
5
6
|
for
i := range valslice {
val := valslice[i]
go func() {
fmt.Println(val)
}()
}
|
对于文章开头提到的那个问题,最简单的解决方案就是在循环内加一个临时变量,并将后面 goroutine 内的 i 都替换为这个临时变量即可:
1
|
server := i
|
总结 。
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对我的支持.
原文链接:https://segmentfault.com/a/1190000010884717 。
最后此篇关于关于Golang中for-loop与goroutine的问题详解的文章就讲到这里了,如果你想了解更多关于关于Golang中for-loop与goroutine的问题详解的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。
发件人:http://blog.nindalf.com/how-goroutines-work/ As the goroutines are scheduled cooperatively, a go
很多时候在用 Go 开发 http 服务器时,我都会遇到这种困境。 假设我想尽快用http statuscode 200响应客户端(然后在后面执行工作),这就是我通常这样做的原因: 我让我的主要 ht
这是代码: import "fmt" func main() { messages := make(chan string, 1) go func(c chan string) {
我正在学习 Golang,但遇到了一些困难。我已经研究过 Google,但没有任何进展。 我编写了一个代码,通过多台服务器的 ICMP 检查 RTT。 它有这样的结构: type Server str
我想运行多个 goroutine,进行一些处理,将结果放入 channel ,当至少有一个 goroutine 完成时,完成所有其他 goroutine 并从 channel 返回结果。 所以,我尝试
我有两个(但以后我会是三个)go 例程来处理来自远程服务器(来自 ampq channel )的传入消息。但是因为它们正在处理相同的数据/状态,所以我想阻止所有其他 go 例程,除了正在运行的例程。
我有一个案例,我从 2 个不同的位置(ES 和 REDIS)读取数据,我需要从最快的源读取一个值,因此我触发了 2 个 goroutines,一个从 ES 获取数据,其他从REDIS获取。 一旦从其中
像这里一样,我创建了一个 go playground 示例:sGgxEh40ev ,但无法正常工作。 quit := make(chan bool) res := make(chan int) go
我是golang的新手,正在研究goroutine。 我写了一个简单的代码,故意使用 goroutine 来划分数字。 首先,我给出基数并继续除它的数,直到它不能被整除 但是,我改变了go split
Main { go routine_1(carryout a time consuming task and return output) go routine_2(wait for output f
我想知道从另一个 goroutine 返回时调用的 goroutine 会发生什么。他们是继续运行还是被终止?这是一个示例代码来说明我的意思: func func() { // Doing s
更具体地说,在我的例子中,我有一个网络服务器和一个全局可访问的结构,网络服务器使用它来生成页面。我有另一个 Goroutine,它总是定期用新值更新该结构。这会引起问题吗?我是否需要实现一种机制来确保
来自 this file ,我不明白为什么函数startWorker会这样写: func (p *WorkerPool) dispatch() { for i := 0; i < p.maxW
我正在学习围棋,但在使用 goroutines 时遇到了问题。这是我的代码 package main import ( "fmt" "sync" "time" ) var co
我收到以下错误,我不明白为什么: 发送:查询 Herefatal 错误:所有 goroutines 都睡着了 - 死锁! 您可以看到我正在调用我使用 goroutine 创建的函数 routine。我
大家好,我正在从 Python3 过渡到 Go,所以我正在尝试重写我创建的库以获得更好的性能。 我面临一个问题,因为我是 Golang XD 中的新手,我使用有限的 API 下载数百个 json,我想
我有以下格式的脚本部分: func main() { for i=0;i<1000000;i++ { go test() } } func test() { a := test
package main func main() { c:=make(chan int) for i:=0; i<=100;i++ {
我正在学习 Go,我的第一个项目是一个简单的 ping 脚本。本质上,我想 ping 一堆 url,并在每个响应时等待 XXX 秒,然后再次 ping。这是删减的代码: func mai
这个问题在这里已经有了答案: Go all goroutines are asleep deadlock (2 个回答) fatal error: all goroutines are asleep
我是一名优秀的程序员,十分优秀!