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条)

报告相同问题?