如何从通道中读取数据一旦我的 GoRoutines 运行完毕?
来源:stackoverflow
时间:2024-02-15 12:36:23 338浏览 收藏
大家好,今天本人给大家带来文章《如何从通道中读取数据一旦我的 GoRoutines 运行完毕?》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!
我目前有两个函数pushnodes(node)和updatenodes(node)。在 pushnodes 函数中,我通过通道推送要在 updatenodes 中使用的值。为了保存准确的通道值,我需要在启动 updatenodes() 之前完成所有 pushnodes go 例程。 goroutines 执行完毕后如何仍然访问通道值?
我不断收到“致命错误:所有 goroutine 都在睡觉 - 死锁!”。请让我知道如何从频道获取这些值。有更好/替代的方法吗?
//pushNodes is a function that will push the nodes values func pushNodes(node Node) { defer wg.Done() fmt.Printf("Pushing: %d \n", node.number) //Choose a random peer node var randomnode int = rand.Intn(totalnodes) for randomnode == node.number { rand.Seed(time.Now().UnixNano()) randomnode = rand.Intn(totalnodes) } //If the current node is infected, send values through the channel if node.infected { sentchanneldata := ChannelData{infected: true, message: node.message} allnodes[randomnode].channel <- sentchanneldata fmt.Printf("Node %d sent a value of %t and %s to node %d!\n", node.number, sentchanneldata.infected, sentchanneldata.message, allnodes[randomnode].number) } //updateNodes is a function that will update the nodes values func updateNodes(node Node) { defer wg.Done() fmt.Printf("Updating: %d\n", node.number) //get value through node channel receivedchanneldata := <-node.channel fmt.Printf("Node %d received a value of %t and %s!\n", node.number, receivedchanneldata.infected, receivedchanneldata.message) // update value if receivedchanneldata.infected == true { node.infected = true } if receivedchanneldata.message != "" { node.message = receivedchanneldata.message } fmt.Printf("Update successful!\n") } //Part of main functions wg.Add(totalnodes) for node := range allnodes { go pushNodes(allnodes[node]) } wg.Wait() fmt.Println("Infect function done!") wg.Add(totalnodes) for node := range allnodes { go updateNodes(allnodes[node]) } wg.Wait()
正确答案
通道的存在(包括已推入其中的任何数据)独立于可能对其进行读取或写入的 goroutine,前提是至少有一个可以读取的 goroutine 仍然存在和/或写入它。 (一旦所有这些 goroutine 都消失了,通道最终将被 gc 回收。)
您的代码示例无法使用(如 already noted),因此我们无法准确说出您出错的位置,但您会收到在此处报告的 fatal
消息:
如果您尝试从最后一个可运行的 goroutine 中的通道读取,使得该 goroutine 进入睡眠状态以等待该通道上的消息,以这种方式go 运行时的其余部分可以确定当前休眠的 goroutine 不会醒来并在该通道上传递消息。例如,假设您总共有 7 个 goroutine 正在运行,其中一个 goroutine 到达以下代码行:
msg = <-ch
其中 ch
是一个开放通道,目前没有可用数据。这 7 个 goroutine 之一到达这一行并阻塞(“进入睡眠状态”),等待剩余的 6 goroutine 之一执行以下操作:
ch <- whatever
这会唤醒第 7 个 goroutine。所以现在只有 6 个 goroutine 可以在 ch
上写入或关闭 ch
。如果剩下的六个 goroutine也通过同一条线,一次一个、几个或全部,并且没有一个发送在通道上或关闭通道时,那些剩余的 goroutine 也会阻塞。当其中最后一个阻塞时,运行时会意识到程序被卡住了,并出现恐慌。
但是,如果剩下的六个 goroutine 中只有五个像这样阻塞,那么第六个 goroutine 会运行一行:
close(ch)
close
操作将关闭通道,导致所有六个“陷入睡眠”的 goroutine 接收到由零值“假”消息 msg
表示的“数据结束”。您还可以使用接收的二值形式:
msg, ok = <-ch
如果通道未关闭且msg
包含真实消息,则ok
在此获取true
,但如果通道关闭且msg
现在包含零-则获取false
重视“假”消息。
因此,您可以:
- 关闭频道以表明您不打算发送任何其他内容,或者
- 仔细匹配“从频道接收”操作的数量与“在频道上发送消息”操作的数量。
前者是通道的常态,无法提前知道应在通道上发送多少条消息。即使您知道,它仍然可以使用。完成关闭的典型构造是:
ch := make(chan T) // for some type T // do any other setup that is appropriate var wg sync.WaitGroup wg.add(N) // for some number N // spin off some number of goroutines N, each of which may send // any number of messages on the channel for i := 0; i < N; i++ { go doSomething(&wg, ch) // in doSomething, call wg.Done() when done sending on ch } go func() { wg.Wait() // wait for all N goroutines to finish close(ch) // then, close the channel }() // Start function(s) that receive from the channel, either // inline or in more goroutines here; have them finish when // they see that the channel is closed.
这种模式依赖于创建额外的第 n+1 个 goroutine 的能力,即匿名函数 go func() { ... }()
序列,其整个工作就是等待所有 发件人说我已发送完毕。每个发送者通过调用 wg.done()
一次来完成此操作。这样,发送者就没有任何关闭通道的特殊责任:他们都只是写,然后在写完后宣布“我写完了”。 一个 goroutine 有一个 特殊职责:它等待所有 发送者宣布“我写完了”,然后关闭通道然后退出,完成了一生中的一项工作。
所有接收者(无论是一个还是多个)现在都可以轻松知道何时不再有人发送任何内容,因为此时他们会看到一个关闭的通道。因此,如果大部分工作都在发送端,您甚至可以在此处使用主 goroutine 和简单的 for ... range ch
循环。
今天关于《如何从通道中读取数据一旦我的 GoRoutines 运行完毕?》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!
-
502 收藏
-
502 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
139 收藏
-
204 收藏
-
325 收藏
-
477 收藏
-
486 收藏
-
439 收藏
-
357 收藏
-
352 收藏
-
101 收藏
-
440 收藏
-
212 收藏
-
143 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 484次学习