So it always guarantees to print "hello world" for the unbuffered channel,
doesn't it?
package main
*var c = make(chan int)*
var a string
func f() {
a = "hello, world"
*c <- 0*
}
func main() {
go f()
*<-c*
print(a)
}
it will guarantee to print "hello, world".
package main
*var c = make(chan int)*
var a string
func f() {
a = "hello, world"
*<-c*
}
func main() {
go f()
* c <- 0*
print(a)
}
it will also guarantee to print "hello, world".
A send on a channel happens before the corresponding receive from that
channel completes.
For the unbuffered channel and the buffered channel.
*A receive from an unbuffered channel happens before the send on that
channel completes.*
Only for the unbuffered channel.
在 2014年5月29日星期四 UTC+8下午10:00:29,Ian Lance Taylor写道:
>
> On Thu, May 29, 2014 at 1:32 AM, liming <[email protected] <javascript:>>
> 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
>
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.