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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化