On Thu, May 29, 2014 at 1:32 AM, liming <
limi...@gmail.com> wrote:
>
> From go’s documentation
>
> If the channel is unbuffered, the sender blocks until the receiver has
> received the value. If the channel has a buffer, the sender blocks only
> until the value has been copied to the buffer; if the buffer is full, this
> means waiting until some receiver has retrieved a value.
>
> The following code is gaurantined to print “hello, world”
>
> package main
> var c = make(chan int, 10)
> var a string
>
> func f() {
> a = "hello, world"
> c <- 0
> }
>
> func main() {
> go f()
> <-c
> print(a)
> }
Right.
> if we change channel c to unbuffered channel:
>
> package main
> var c = make(chan int)
> var a string
>
> func f() {
> a = "hello, world"
> c <- 0
> }
>
> func main() {
> go f()
> <-c
> print(a)
> }
>
> Is it gaurantined to print “hello, world”
Yes.
> c<-0 will bock until <-c has received the value,
> so c<-0 happens before <-c, as the assignment to a happens before c<-0,
> so in the main function, it will print “hello, world” right?
Right.
> But from go memory model, it says
> A receive from an unbuffered channel happens before the send on that channel
> completes.
>
> so print(a) in main function is not gaurantined to print “hello, world”
No. The memory model also says "A send on a channel happens before
the corresponding receive from that channel completes." So the send
starts to happen, then the receive completes, then the send completes.
Ian