On Wed, Jul 20, 2022 at 01:00:59PM +0300, Konstantin Khomoutov wrote:

> > for i=0;i<10;i++ { go func () { /* const c=i OR var v=i */
> >  fmt.Println("f:beg i=",i) // here c or v instead 
> > // action 
> >  fmt.Println("f:end i=",i) // here c or v instead 
> > }}

[...]

>  - Make your anonymous functions not close over that shared variable.
> 
>    This can be done by defining one or more arguments in the function's
>    definition and pass the values the function has to operate on via that
>    parameters when calling it. Since passing of parameters is done via
>    copying them, each anonymous function will have their own copies.
> 
>    In your simple case you could do what PeterGo proposed - something like:
> 
>    go func (int i) { ... }(i)

[...]

While we are at it, pay attention to the fact that variable assignments and
passing parameters to functions always copy values, some types contain
pointers - addresses of other variables - and hence copying of them copies
those pointers, not the memory they point at. Sometimes it is said that such
types have reference semantics.

Examples of such types are slices and maps. For instance, if in our toy
example we'd make our anonymous function receive a slice variable and pass
it a slice value when calling it to execute in a separate goroutine, the
slice itself would be copied but the memory of its backing array would not -
only the address of that memory block. Hence if we were to start multiple
goroutines this way, and at least one of them would attempt to mutate the
slice, that, again, could produce a data race (and generally weird behavior -
if some goroutine were to append to the slice, and it was required to grow).

To recap, when pondering how to make your goroutines not step on each other's
memory toes, you have to consider how the types the variables of which these
goroutines intend to manipulate, are defined, and which properties they have.

-- 
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.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/20220720110832.qwuszqutgf7o2bpp%40carbon.

Reply via email to