如果在 Go 中通过通道发送一个大结构体,它实际上是在 goroutines 之间复制的吗?例如,在下面的代码中,Go 是否会在 goroutine 的生产者和消费者之间复制所有 largeStruct 数据?package mainimport ( "fmt" "sync")type largeStruct struct { buf [10000]int}func main() { ch := make(chan largeStruct) wg := &sync.WaitGroup{} wg.Add(2) go consumer(wg, ch) go producer(wg, ch) wg.Wait()}func producer(wg *sync.WaitGroup, output chan<- largeStruct) { defer wg.Done() for i := 0; i < 5; i++ { fmt.Printf("producer: %d\n", i) output <- largeStruct{} } close(output)}func consumer(wg *sync.WaitGroup, input <-chan largeStruct) { defer wg.Done() i := 0LOOP: for { select { case _, ok := <-input: if !ok { break LOOP } fmt.Printf("consumer: %d\n", i) i++ } }}游乐场:http : //play.golang.org/p/fawEQnSDwB
2 回答

不负相思意
TA贡献1777条经验 获得超10个赞
是的,Go 中的一切都是副本,您可以通过将通道更改为使用指针(又名chan *largeStruct
)来轻松解决该问题。
// 演示:http : //play.golang.org/p/CANxwt8s2B
如您所见,指向的指针v.buf
在每种情况下都不同,但是如果将其更改为chan *largeStruct
,则指针将相同。
@LucasJones 提供了一个更容易理解的例子:https : //play.golang.org/p/-VFWCgOnh0
正如@nos 指出的那样,如果您在发送后修改两个 goroutine 中的值,则存在潜在的竞争。
- 2 回答
- 0 关注
- 209 浏览
添加回答
举报
0/150
提交
取消