It's neither meaningful nor safe. :)

Since you're writing a variable that can be read in another goroutine 
without establishing any sort of ordering, this code is unsafe. The issue 
happens with any code like:

func main() {
  var ch chan int
  go func() { <-ch }()
  ch = make(chan int)
}

The spawned goroutine's read of `ch` isn't ordered with respect to the 
write of `ch` in the main goroutine, so you have a data race. You can 
verify this yourself by running the above code with `go run -race main.go`. 
(Also note that, if you move the assignment of `ch` above the `go func() 
...`, the race goes away. That's because starting a goroutine enforces an 
order of events).

Next, quoting [the spec](https://golang.org/ref/spec#Select_statements): 
"For all the cases in the [select] statement, the channel operands of 
receive operations [...] are evaluated exactly once."

So, it seems that the compiler is required to save the value of `signal` as 
soon as you enter your `select` statement. As a result, when you update it 
later, none of the goroutines that were in the `select` statement would 
notice, since they're all trying to read from the original "blocked" 
channel. See: https://play.golang.org/p/jpe_oNHGGY

George

On Saturday, September 3, 2016 at 6:39:27 AM UTC-7, Uvelichitel wrote:
>
> Hi. 
> Closing channel to broadcast Cancellation or Done event is proven 
> pattern in Go. 
>
>      go func(){ 
>          for{ 
>              select{ 
>                  case <-signal: 
>                      //canselation 
>                  default: 
>                      //default 
>              } 
>          } 
>      } 
>      //... 
>      close(signal) 
>
> But we can signal only once this way. May we cheat a bit? 
>
>      var closed = make(chan struct{}) 
>      close(closed) 
>      var blocked chan struct{} 
>      var signal chan struct{} 
>      //and than switch to emit events 
>      signal = closed 
>      //... 
>      signal = blocked 
>      //... 
>      signal = closed 
>      //... 
>      signal = blocked 
>
> Does it considered meaningful or/and at least safe? 
> -- 
> Ilya Kostarev 
>

-- 
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+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to