douxian7534 2014-09-26 02:37
浏览 58
已采纳

如何有效地将goroutine中分配的结构通过通道传递回主例程?

At a basic level, I have a main routine that spawns multiple goroutines to process data. Every time a goroutine processes the data it sends back a struct of varying size (it contains slices and/or arrays allocated from within the goroutine each time).

The data isn't huge (say, a few megabytes) but in general is it more efficient (and is it safe) to transfer a pointer to the data versus a copy of it all? If the data structure is static and I transfer a pointer to it, there's a risk that the structure may change while I'm still processing the result of the previous invocation (if it's fully reallocated then perhaps that's not an issue).

  • 写回答

2条回答 默认 最新

  • dongtiao2066 2014-09-26 02:49
    关注

    It's OK and common to send pointers to values. If the value is large, sending a pointer to the value will be more efficient than sending the value. Run a benchmark to find out how large is "large".

    The caveat is that you must prevent unsafe concurrent access to the value. Common strategies for preventing unsafe concurrent access are:

    • Pass ownership of the value from the sender to the receiver. The sender does not access the value after sending it. The receiver can do whatever it wants with the value.
    • Treat the value as read only after sending. Neither the sender or receiver modifies the value after sending.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解
  • ¥15 有偿请教计算电磁学的问题涉及到空间中时域UTD和FDTD算法结合的
  • ¥15 three.js添加后处理以后模型锯齿化严重
  • ¥15 vite打包后,页面出现h.createElement is not a function,但本地运行正常