I know what it is. The closure is implicitly receiving the variable by 
value, so its state when the goroutine spawns is fixed into its local scope.

If you moved that variable outside of the function you would not have this 
problem, as another alternative solution.

Incidentally, the issue of stale pass-by-value and even can be stale 
pointers if the pointer is changed is a low visibility serious security 
problem. Using a pointer would also solve the problem here.

I have become very leery of the := operator recently as I have noticed that 
it is one of the most frequent logic bugs in my code, for which reason I 
want to write a linter/pretty printer that removes them and places them at 
root scope, then the programmer will see name collisions. These can be 
avoided by instead pre-declaring a set of temporary variables that you 
assume need to be zeroed when they are used in an algorithm. A simple 
function with type switch could cover all builtins easily.

Another thought occurs also, since I am quite confused still about the 
value vs reference mechanism behind array variable parameter passing, since 
theoretically that code should not have this issue as it should be getting 
passed around as a pointer transparently. So it could be a logic error in 
the implementation of slices, I have seen this one also come up a lot and 
thus am completely confused about the situations when the very same thing 
happens (stale values on slices).

On Sunday, 17 February 2019 14:59:34 UTC+1, Manlio Perillo wrote:
>
> Your program has a data race, since you are accessing the array from two 
> different goroutines.
>
> Manlio
>
> On Saturday, February 16, 2019 at 3:29:45 PM UTC+1, Hemant Singh wrote:
>>
>> I have the following program.  The program is processing network packets 
>> at 1 Gbps rate.  I don't want to print the rate for every packet.  Instead, 
>> I'd like to save the rate in an array and dump the array on Ctrl-c of the 
>> program.  When I dump the array on Ctrl-c, the data is all zeroes.  Please 
>> see "<===" in the program below.  Anything else one could do?
>>
>> Thanks.  
>>
>> -Hemant
>>
>> func main() {
>>
>>   const SZ = 65536
>>   var time_array [SZ]float64
>>
>>   c := make(chan os.Signal)
>>   signal.Notify(c, os.Interrupt, syscall.SIGTERM)
>>
>>   go func() {
>>      <-c
>>      fmt.Printf("You pressed ctrl + C. User interrupted infinite loop.")
>>      fmt.Printf("%v ", time_array);  <=== all zeroes printed. 
>>      os.Exit(0)
>>   }()
>>
>>
>>   i := 0
>>   for {
>>     ...
>>     time_array[i] = rate
>>     fmt.Printf("%f bps ", rate) <=== value printed is correct. 
>>     i++
>>   }
>> }
>>
>>

-- 
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