Monday, April 29, 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 on the lookout for. This publish about potential race situations appears a possible match.

I’ve been 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 straightforward to see.

package deal major

import (
	"fmt"
)

sort Particular person struct {
	Title string
	Age  int
}

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

func major() {

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

	ch := make(chan Particular person)

	go SendPerson(ch, p)

	title := (<-ch).Title
	fmt.Println(title)
}

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

SendPerson {John 23}
John

I don’t fairly perceive why. I believed 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 needed 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 generally? I’d anticipate to see it at all times or by no means, however not generally seemingly at random. I’m not certain if that is related to being buffered or unbuffered.

Can any individual level me in the proper route?

Many thanks,
John.

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

When the Primary 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