edge cases. I understand for a successful transaction to occur in a channel, A sender and a receiver must be available, for a given “message”.
Why does the following operation not result in a deadlock?
package main
func main() {
messages := make(chan string)
// A go routine that sends to a channel
go func() {
messages <- "I am sending a message."
}()
// Main routine has no receiver.
// No compilation or runtime error.
// Why doesn't it deadlock?
}
because your main goroutine doesn't wait, returns and the program is terminated
so if I understand correctly deadlock will only occur if you try to access the channel without goroutines because the channel has no buffer.
package main func main() { messages := make(chan string) // A go routine that sends to a channel //go func() { messages <- "I am sending a message." //}() }
if you make a buffered channel it will work messages := make(chan string, 1)
main would have exited by then
Yes, I did play with buffer sizes. Unless I misunderstood, I read somewhere that buffer channels have their time and place. To limit their use and rather keep the code “tightly coupled” for each successful channel transaction to occur (or something). Is that a valid point?
When using buffering there is no need to use goroutine for example. When we don't have a buffer on the channel, the use of goroutines is mandatory.
Thanks, Yes, I understand that bit but the point I wrote just earlier, is that a valid consideration at all? That to use buffer only if the solution really requires of the channel to hold a few messages?
Yes, adaptation by need and problems we know the amount to be shared.
Обсуждают сегодня