Is the structure actually copied between goroutines if it is sent via the Golang channel?

If a large structure is sent down the channel in Go, is it really being copied between goroutines?

For example, in the code below, will Go actually copy all largeStruct data between the goroutines producer and the 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\n", 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\n", i) i++ } } } 

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

+5
source share
2 answers

Yes, this is all a copy in Go, you can easily get around this 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 bit easier to follow the example: https://play.golang.org/p/-VFWCgOnh0

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

+11
source

Go programming language specification

Send reports

The send statement sends the value through the channel. The expression of the channel must be of the type of the channel, the direction of the channel must allow the sending of the operation, and the type of value to be sent must be related to the type of element of the channel.

This is a copy because the value is passed to the channel by assigning to the channel element type. If the value is struct, then the structure is copied. If the value is a pointer to a structure, then the pointer to the structure is copied.

+4
source

Source: https://habr.com/ru/post/1244581/


All Articles