On Sunday, 1 May 2022 at 07:04:34 UTC+1 yan.z...@gmail.com 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 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/7b197eb6-775e-456b-abf9-30ab00becec9n%40googlegroups.com.

Reply via email to