K
K
Kirill Novak2022-03-31 13:44:42
go
Kirill Novak, 2022-03-31 13:44:42

Are there pitfalls in using Golang references in goroutines?

Hello. I have code where I iterate over the elements in a list, using those elements in a goroutine that I run inside a loop. I want to safely pass a value to a goroutine, but I discovered a feature that if you pass a reference to a goroutine, the goroutine will have the most recent value of the variable in the loop (if enough time has passed and the loop has completed before the reference is accessed).

Is that how it should be? Are there any other points I should be aware of? Would it then be sufficient to simply not use references in loops, or is there something else to be aware of?

Code - https://play.golang.com/p/5phJY4x5Yaf

As a result of the code execution, it will be seen that in the case of using links - under each i 0 will be displayed - the value of the last element in the list. If there are no links, then everything is ok.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Z
Zolg, 2022-03-31
@kinojs

but I discovered a feature that if you pass a link to a goroutine, the goroutine will have the most recent value of the variable in the loop
it's not a 'feature', it's the main feature of links. In any JAP.
The variable itself is some area in memory that contains what is contained in this variable.
When passing a parameter by value ('without references'), another such area is created in memory, where the contents of the original variable are copied. And the code of the called function works already with its copy.
When passing a parameter by a pointer ('with references'), a copy of the variable is not created, and the address (pointer, reference) of the memory area in which the original variable is located is passed to the called function. And the called function works already with it.
Obviously, when two pieces of code can write and read to the same memory location at the same time, they instantly 'see' the changes made by each.
And, of course, in the general case, without additional effort, this is not a thread / goroutine / etc. safe. Moreover, if the variable itself is something more complicated than int, then the effect of such simultaneous work can be much more entertaining than just changing the value.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question