Hi Brian!

I just checked my previous code for race errors. It turned out that a `map`
is very hard to avoid the race condition.

I have already put reading and writing into different functions with a
global lock.

The reading basically sends the struct wrapped map to a channel. Then there
is another goroutine processes the struct which contains the map.

The race condition did not happen between the writing function and reading
function, but instead the writing function and the processing goroutine.

So that indicates neither wrapping the map inside a struct nor passing it
through a channel did not make a copy of the map at all. It is the very
same map that go runtime manages. It is like only the memory address of the
map gets embedded in the struct and then passed over.

Do you know any way in go to copy a map? Or the only way to do it is to use
json Marshal and Unmarshal?

Thanks,
   Zhaoxun

On Sun, May 1, 2022 at 6:45 PM Brian Candler <[email protected]> wrote:

> On Sunday, 1 May 2022 at 07:04:34 UTC+1 [email protected] wrote:
>
>> Any advice?
>>
>
> If the value you are trying to read and update is int32 or int64, you can
> use the sync.Atomic <https://pkg.go.dev/sync/atomic> package.
>
> However, if you feel you need to do this all the time, I can't help but
> wonder that you're approaching Go from the wrong angle.  The solution is
> not to protect concurrent accesses to global variables; it is to get rid of
> the global variables.  Use channels instead.  Share memory by
> communicating; don't communicate by sharing memory.
>
> https://www.youtube.com/watch?v=5zXAHh5tJqQ
>
> > I am not sure if map type needs such special care since I heard map is
> okay as one goroutine reads it while another writes it at the same time.
>
> No, quite the opposite: multiple goroutines accessing the same map
> concurrently are very likely to cause a panic.  There is sync.Map
> <https://pkg.go.dev/sync#Map> you can use safely from multiple goroutines.
>
> --
> You received this message because you are subscribed to a topic in the
> Google Groups "golang-nuts" group.
> To unsubscribe from this topic, visit
> https://groups.google.com/d/topic/golang-nuts/4AW1Ss9Tjp0/unsubscribe.
> To unsubscribe from this group and all its topics, send an email to
> [email protected].
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/golang-nuts/7b197eb6-775e-456b-abf9-30ab00becec9n%40googlegroups.com
> <https://groups.google.com/d/msgid/golang-nuts/7b197eb6-775e-456b-abf9-30ab00becec9n%40googlegroups.com?utm_medium=email&utm_source=footer>
> .
>

-- 
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 [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CADEX6_UWwdqtuQc9Tbo7BgtvCP_CNE-NjbrZ%3Drvp2WBY8%2B8bkg%40mail.gmail.com.

Reply via email to