Why is the error sent to original channel can still be received after recreating the channel?

117 views
Skip to first unread message

Feng Liyuan (SunRunAway)

unread,
Sep 19, 2024, 4:48:53 PM9/19/24
to golang-nuts

I have a piece of Go code where I create a buffered error channel and send an error to it from a goroutine. Then, in the main, I recreate this channel. To my confusion, even after recreating the channel, I still receive the error sent by the original goroutine. Here is the code:

https://go.dev/play/p/y3roOPKO0iy

Can someone help explain why this happens?

robert engels

unread,
Sep 19, 2024, 4:52:46 PM9/19/24
to Feng Liyuan (SunRunAway), golang-nuts
Because the channel is captured by reference, so when the Go routine runs it already has the later value.

Your code has a race condition - run it under the race detector.

--
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 golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/3a49b432-a8fa-4bb3-bcd2-a8fcd679a0c3n%40googlegroups.com.

Justin Israel

unread,
Sep 19, 2024, 5:51:25 PM9/19/24
to golang-nuts
On Friday, September 20, 2024 at 8:52:46 AM UTC+12 robert engels wrote:
Because the channel is captured by reference, so when the Go routine runs it already has the later value.

Maybe this modified version better illustrates the problem:
https://go.dev/play/p/XLekzv9wsVO

The original code has no synchronization, so you cannot be sure when the goroutine will run and reference the channel from the outer scope. This updated example shows the difference between synchronizing before and after the goroutine.
Reply all
Reply to author
Forward
0 new messages