Geln Yang
Geln Yang

Reputation: 912

trying to understand golang chan cause crash or do something else

The following is a example from https://golang.org/ref/mem:

var c = make(chan int)
var a string

func f() {
    a = "hello, world"
    <-c
}
func main() {
    go f()
    c <- 0
    print(a)
}

is also guaranteed to print "hello, world". The write to a happens before the receive on c, which happens before the corresponding send on c completes, which happens before the print.

If the channel were buffered (e.g., c = make(chan int, 1)) then the program would not be guaranteed to print "hello, world". (It might print the empty string, crash, or do something else.)

I understand that It might print the empty string, but not for crash or do something else, when will crash happen? And when will it do something else ?

Upvotes: 2

Views: 439

Answers (1)

Grzegorz Żur
Grzegorz Żur

Reputation: 49221

A string in Go is a read only slice of bytes. Slice consists of length an pointer. Let's assume that we first set length to a large value and then change the pointer. The other go routine may first read new length and old pointer. Then it tries to read over the end of the previous string. It either read some garbage or is stopped by operating system and crashes.

The order of operations does not matter really, if you set pointer firsts it may point to memory area too short for the current length.

Upvotes: 4

Related Questions