doutan3371 2016-03-07 13:55
浏览 77
已采纳

如果通过Golang通道发送,实际上在goroutine之间复制了一个结构吗?

If a large struct is sent over a channel in Go, is it actually copied between goroutines?

For example, in the code below, will Go actually copy all largeStruct data between goroutines producer and consumer?

package main

import (
    "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
", i)
        output <- largeStruct{}
    }
    close(output)
}

func consumer(wg *sync.WaitGroup, input <-chan largeStruct) {
    defer wg.Done()
    i := 0
LOOP:
    for {
        select {
        case _, ok := <-input:
            if !ok {
                break LOOP
            }
            fmt.Printf("consumer: %d
", i)
            i++
        }
    }
}

Playground: http://play.golang.org/p/fawEQnSDwB

  • 写回答

2条回答 默认 最新

  • doubian19900911 2016-03-07 14:07
    关注

    Yes, everything is a copy in Go, you can easily work around that by changing the channel to use a pointer (aka chan *largeStruct).

    // demo: http://play.golang.org/p/CANxwt8s2B

    As you can see, the pointer to v.buf is different in each case, however if you change it to chan *largeStruct, the pointers will be the same.

    @LucasJones provided a little easier to follow example: https://play.golang.org/p/-VFWCgOnh0

    As @nos pointed out, there's a potential race if you modify the value in both goroutines after sending it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 怎样才能让鼠标沿着线条的中心线轨迹移动
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?