duanjiao6711 2017-08-04 21:34
浏览 209
已采纳

Golang:具有只读访问权限的包作用域变量是否需要互斥锁?

If I have a package-scoped variable like this:

var (
    bus *Bus // THIS VARIABLE
)

// Bus represents a repository bus. This contains all of the repositories.
type Bus struct {
    UserRepository *UserRepository
    // ...
}

...and I give access to the bus variable on my repositories so that they can access each other, do I need to use any sort of mutex if they can be used concurrently?

Quick pseudocode of what would happen:

// Router
router.GET("/user/:id", c.FindUser)

// Controller
func (c *UserController) FindUser(w http.ResponesWriter, r *http.Request) {
    w.Write([]byte(c.UserService.FindUser(r.Get("id"))))
}

// Service
func (s UserService) FindUser(id int) *domain.User {
    return s.UserRepository.FindByID(id) 
}

// Repository
func (r UserRepository) FindByID(id int) *domain.User {
    // This is where the package-scope `bus` variable will be used
}

In the FindByID function, I may use the package-scoped bus variable, which of course can be accessed concurrently since it will be called whenever an HTTP request triggers it, and those are all handled concurrently.

  • 写回答

1条回答 默认 最新

  • doujie9252 2017-08-05 00:47
    关注

    If all you do is reading the content of variable - then no, you do not need mutex. However, if you ever mutate its state, then you need to protect it.

    Two concurrent writes or concurrent write and read can cause problems. If your writes are rare, you might want to use RWMutex. It will allow multiple readers to access, but not together with a writer.

    Also, check out race detector. It is best effort detector, so it does not guarantee that you do not have race condition, but it can detect some use cases. Also note that you need to cause race in order for race detector to detect it, so writing tests that use your bus concurrently or simulating real conditions has to be done.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 outlook无法配置成功
  • ¥15 Pwm双极模式H桥驱动控制电机
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换