Saturday, May 4, 2024
HomeGolangA query about channels - Getting Assist

A query about channels – Getting Assist


Hello,

I hope this isn’t a boneheaded query. I’ve searched on this discussion board however haven’t seen fairly what I’m in search of. This submit about potential race circumstances appears a possible match.

I’ve been taking a look at channels on golangdocs.com, sending customized information through channels. I’ve made one tiny change, including a Printf assertion to the known as perform. I’ll paste the entire code right here so it’s simple to see.

package deal principal

import (
	"fmt"
)

kind Particular person struct {
	Identify string
	Age  int
}

func SendPerson(ch chan Particular person, p Particular person) {
	ch <- p
	fmt.Printf("SendPerson %vn", p)
}

func principal() {

	p := Particular person{"John", 23}

	ch := make(chan Particular person)

	go SendPerson(ch, p)

	identify := (<-ch).Identify
	fmt.Println(identify)
}

If I run this code just a few instances I often see simply John. Typically I see:

SendPerson {John 23}
John

I don’t fairly perceive why. I assumed this was an error on my half as I ought to have put the Printf assertion within the known as perform earlier than the channel dealing with half as a result of I wished to see what I used to be receiving (that was the aim of including the Printf within the first place). However then I considered it a bit extra. Why do I see this typically? I’d anticipate to see it all the time or by no means, however not typically seemingly at random. I’m not certain if that is related to being buffered or unbuffered.

Can anyone level me in the best path?

Many thanks,
John.

Hello @MrJohn
The SendMessage perform (and goroutine) ends earlier than it could possibly print the message.
Attempt to print after which ship the message to the channel.

When the Important perform finalize, it kills all of the others goroutines.
It’s like a race situation.

Hello @GonzaSaya,

Thanks, I guessed it was a race situation. However I didn’t fairly perceive why.

Thanks once more.
John.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments