前段时间项目中存在多个goroutine并发读写同一个变量,对是否要保证原子性产生了困惑
问了组里的大佬,得出的结论是,一般对于常规变量、指针或者结构体的变量进行同时读写,是不用加锁的,顶多是读“脏”,看具体业务逻辑这种脏数据是否允许的。
但是还是无法完全解答我的困惑,于是search了一下,看到一些相关问题如下:
- Is it safe to read a function pointer concurrently without a lock?
- Do I need to hold a lock of a struct to read the member concurrently?
- golang struct concurrent read and write without Lock is also running ok?
结论就是并发读写一个variable会导致undefined behavior,最好还是避免吧。这里的varible包括普通的变量、指针、结构体变量等,参见Golang variable