Questions about goroutines

Hello everyone, I’m pretty new to Go, I’m learning it from Go By Example and I’m currently on the Closing Channels section.

I understand the closing part and how the whole code works, which is, since the anonymous function is working asynchronously and running an infinite loop, as soon as the main process sends a message (which is a decimal) on jobs (which is a buffered channel), the worker, using an infinite loop, catches it and prints the correct number and sends back a signal on done when the message channel (jobs) is closed or when it reaches the end of it.
Phew, please, correct me if I’m wrong, I’m having a whole new concept about programming from learning Go.
Then we wait for the goroutine using <-done. About this part, is it really necessary? Because when I comment it out, whatever I print after it still gets printed after all the workers are done, I thought it would be the opposite. Why is that?

So my last question is, this piece of code looks really interesting! Can someone show me some good real world examples using this technique?

I just realized that when I remove the <-done part which awaits the goroutine, the sender and the receiver are not synchronized anymore. I don’t understand why :confused:, I thought it was only there to wait on the goroutine to finish, but it seems like it makes them go in order.

Haha, I was wrong, they still don’t go in order sometimes even with <-done. I guess I just need some more practice. I’ll just keep going and see.

Goroutines, by themselves, are not guaranteed to run in any particular order, or at all.

Here the sender and receiver are not synchronized because jobs is buffered. On an unbuffered channel, the sender blocks until the message is received.

The Printlns also only give a rough indication of synchronization, as the channel operation and the Println are not atomic. This means that some other goroutine could run after the job is sent and before the Println is called.

The only synchronization in the example is accomplished with done.

It is best to not make assumptions about when goroutines run. If the program needs to know, for example, that all the jobs have been received, then use unbuffered channels or another synchronization primitive to guarantee that the goroutine has progressed that far.

Hope this helps.

1 Like

Wow, makes total sense. Thank you!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.