管理 golang 中的 goroutine 并接收响应
在 Go 语言中管理 goroutine 是并发编程的关键,本文探讨了如何通过 goroutine 获取响应并处理错误。通过使用通道和错误传播,开发者可以异步调用 goroutine,同时在主线程中接收结果或错误信息。这使得应用程序可以响应事件,处理流数据,并在 goroutine 失败时提供适当的响应,从而提高并发性并增强用户体验。
我在 getposition、getstatus 和重新路由中调用了 go 例程,目前我正在主函数中调用 go getstatus,该函数具有 go func(),它处理流 grpc 和 sse 的事件。
目前这是我的代码,我尝试过
func getpositioncontext(ctx context.context, uav pb.uavcontrollerclient, uavid *pb.uavid, projectid string) {
log.printf("getposition start")
stream, err := uav.getposition(ctx)
if err != nil {
fmt.printf("error getposition:%s", err.error())
}
streamid, eventname := eventssubscribe(projectid, uavid.aircraft, "get_position")
position := make(chan models.droneposition)
// 受信ループ開始
go func() {
fmt.print("start getposition loop")
for {
msg, err := stream.recv() // msg uavposition
if err == io.eof {
// read done.
fmt.print("start getposition loop closed")
close(position)
return
}
if err != nil {
log.fatalf("failed to receive getposition : %v", err)
close(position)
return
}
// log.printf("position point[%s](%f, %f, %f) h:%f", uavid.aircraft, msg.latitude, msg.longitude, msg.altitude, msg.heading)
waypoint := models.waypointitem{
latitude: msg.latitude,
longitude: msg.longitude,
altitude: msg.altitude,
heading: msg.heading,
}
droneposition := models.droneposition{
name: uavid.aircraft,
itemparameter: waypoint,
}
// publish to eventgo
publishnotif(droneposition, streamid, eventname)
return
}
}()
startmsg := pb.uavcontrollerpositionrequest{
uavid: uavid,
instruction: true,
interval: 2,
}
fmt.print("send getposition start")
if err := stream.send(&startmsg); err != nil {
log.fatalf("failed to send getposition: %v", err)
}
<-position
stream.closesend()
fmt.print("end of getposition")
}
这是我调用这个函数的部分
go utils.getposition(ctx, uavservice, &uavid, projectid)
我想从 go func 获取返回值,就像 grpc 服务器中一切正常一样,没有问题,我应该返回 200 成功,如果失败则返回 500。
for {
time.sleep(time.duration(60) * time.second)
}
调用后我有这个代码,它应该每 10 秒返回一次成功
return c.JSON(500, failed or pass)
当流部分正在工作时,如果 go 例程成功或失败,我希望有一些东西返回到 ui,以便响应不会挂起,否则其他 api 调用将无法工作。
解决方案
如果你想知道在 getpositioncontext 中处理 go func() 时是否出现错误,那么你可以执行如下操作。我修改了所有错误以冒泡,而不是调用 log.fatal。顺便说一句,推迟 stream.closesend() 可能是明智的,但我缺少上下文,而且它超出了问题的范围。
我已尽力理解这个问题,但如果我遗漏了什么,请告诉我!
代码已被修改为直接在 getpositioncontext 中冒泡错误,而不是调用 log.fatal。此外,如果 go func() 中出现错误,它将通过通道发送回 getpositioncontext,然后返回给调用者。
func getpositioncontext(ctx context.context, uav pb.uavcontrollerclient, uavid *pb.uavid, projectid string) error {
log.printf("getposition start")
stream, err := uav.getposition(ctx)
if err != nil {
return fmt.errorf("error getposition: %v", err.error())
}
streamid, eventname := eventssubscribe(projectid, uavid.aircraft, "get_position")
errc := make(chan error)
// 受信ループ開始
go func() {
fmt.print("start getposition loop")
for {
msg, err := stream.recv() // msg uavposition
if err == io.eof {
// read done.
fmt.print("start getposition loop closed")
close(errc)
return
}
if err != nil {
errc <- fmt.errorf("failed to receive getposition : %v", err)
return
}
// log.printf("position point[%s](%f, %f, %f) h:%f", uavid.aircraft, msg.latitude, msg.longitude, msg.altitude, msg.heading)
waypoint := models.waypointitem{
latitude: msg.latitude,
longitude: msg.longitude,
altitude: msg.altitude,
heading: msg.heading,
}
droneposition := models.droneposition{
name: uavid.aircraft,
itemparameter: waypoint,
}
// publish to eventgo
publishnotif(droneposition, streamid, eventname)
// did you mean to return here? the for loop will only ever execute one time.
// if you didn't mean to return, then remove this close
close(errc)
return
}
}()
startmsg := pb.uavcontrollerpositionrequest{
uavid: uavid,
instruction: true,
interval: 2,
}
fmt.print("send getposition start")
if err := stream.send(&startmsg); err != nil {
return fmt.errorf("failed to send getposition: %v", err)
}
err = <- errc
stream.closesend()
fmt.print("end of getposition")
return err
}
如果你想异步调用这个函数,但仍然想知道是否有错误,那么你可以执行以下操作。
errC := make(chan error)
go func() {
errC <- GetPositionContext(..........)
}()
// Do some other stuff here
// Until you need the result
err := <- errC
// ... and Eventually when you want to return the success or failure as JSON
if err != nil {
return c.JSON(500, failed)
}
return c.JSON(500, pass)到这里,我们也就讲完了《管理 golang 中的 goroutine 并接收响应》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!
如何在 Go for 循环的 post 部分中添加条件以结束循环?
- 上一篇
- 如何在 Go for 循环的 post 部分中添加条件以结束循环?
- 下一篇
- 在C++结构中实现类似Golang的代码提示/标签
-
- Golang · Go问答 | 5小时前 | go · https · net/http · GetCertificate TLS配置 Go ServeTLS TLSConfig.Certificates GetConfigForClient 内存证书
- Go http.Server.ServeTLS 证书文件为空时如何使用 TLS 配置
- 168浏览 收藏
-
- Golang · Go问答 | 5小时前 | 标准库 · 错误处理 · Go问答 · Go Content-Type mime.ParseMediaType ErrInvalidMediaParameter
- Go mime.ParseMediaType 返回类型和错误同时存在时该怎么处理
- 374浏览 收藏
-
- Golang · Go问答 | 5小时前 |
- Go http.Server.ConnContext 怎么为每条连接附加自定义元数据
- 313浏览 收藏
-
- Golang · Go问答 | 5小时前 |
- Go http.Server.ErrorLog 怎样接管服务器内部错误输出
- 151浏览 收藏
-
- Golang · Go问答 | 5小时前 |
- Go httptest.NewRequestWithContext 怎样测试请求上下文取消
- 230浏览 收藏
-
- Golang · Go问答 | 5小时前 |
- Go testing/quick.Check 失败后怎样复现同一组输入
- 352浏览 收藏
-
- Golang · Go问答 | 5小时前 |
- Go testing/quick.Value 为什么会拒绝含未导出字段的结构体
- 236浏览 收藏
-
- Golang · Go问答 | 5小时前 | go · Go GOOS go/build Context.MatchFile 文件名约束
- Go go/build.MatchFile 为什么会受 GOOS 和文件名约束影响
- 261浏览 收藏
-
- Golang · Go问答 | 5小时前 |
- Go ast.FilterFile 过滤声明时为什么会删除导入
- 417浏览 收藏
-
- Golang · Go问答 | 6小时前 |
- Go go/doc.ToText 如何把注释格式化成终端文本
- 250浏览 收藏
-
- Golang · Go问答 | 6小时前 | 标准库 · go · Go go/doc.Filter 文档树 未导出声明 公开API
- Go go/doc.Filter 怎样从文档树中移除未导出声明
- 178浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
-
- PubMedQA
- 深入了解PubMedQA生物医学问答数据集,涵盖其核心功能、使用方法及在临床决策、药物研发等场景的应用,助力提升NLP模型性能。
- 455次使用
-
- H2O EvalGPT
- H2O EvalGPT是H2O.ai推出的开源LLM评估平台,提供详细的大模型性能排行榜、行业特定基准测试及A/B测试功能,助您快速选择最适合项目的高性能大语言模型。
- 521次使用
-
- LMArena
- LMArena是加州大学伯克利分校推出的AI模型匿名评测平台。通过盲测投票机制,用户可对比不同大模型回答并生成实时排行榜,助力开发者优化模型及用户选择最佳AI工具。
- 536次使用
-
- HELM
- 深入了解斯坦福推出的HELM(Holistic Evaluation of Language Models)大模型评测体系。本文解析其核心功能、安装配置步骤及应用场景,涵盖准确性、公平性、鲁棒性等多维度指标,助力开发者全面优化语言模型性能。
- 483次使用
-
- MMBench
- MMBench是由上海人工智能实验室等机构联合推出的多模态基准测试平台,提供细粒度能力评估、大规模数据集及VLMEvalKit工具。本文详细介绍其核心功能、安装使用方法及应用场景,助力开发者全面评估多模态模型性能。
- 304次使用
-
- 用Nginx反向代理部署go写的网站。
- 2023-01-17 502浏览
-
- GoLand调式动态执行代码
- 2023-01-13 502浏览
-
- Go crypto/rand.Text 的长度为什么不是固定字符数
- 2026-10-04 501浏览
-
- Go strings.ToValidUTF8 清洗日志内容的边界
- 2026-10-03 501浏览
-
- Go tls.GetCertificate 为什么收不到空 ServerName 请求
- 2026-09-27 501浏览

