Golang:是具有只读访问权限的包范围变量所需的互斥锁吗?

Lan*_*ara 0 go

如果我有这样的包范围变量:

var (
    bus *Bus // THIS VARIABLE
)

// Bus represents a repository bus. This contains all of the repositories.
type Bus struct {
    UserRepository *UserRepository
    // ...
}
Run Code Online (Sandbox Code Playgroud)

...我可以访问bus我的存储库中的变量,以便它们可以相互访问,如果它们可以同时使用,我是否需要使用任何类型的互斥?

会发生什么的快速伪代码:

// 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
}
Run Code Online (Sandbox Code Playgroud)

FindByID函数中,我可以使用package-scoped bus变量,当然可以同时访问它,因为只要HTTP请求触发它就会被调用,并且这些变量都是并发处理的.

del*_*boy 5

如果您所做的只是读取变量的内容 - 那么不,您不需要互斥锁.但是,如果你改变它的状态,那么你需要保护它.

两次并发写入或并发写入和读取可能会导致问题.如果您的写入很少,您可能想要使用RWMutex.它允许多个读者访问,但不能与作者一起访问.

另外,检查比赛检测器.它是尽力而为的探测器,因此它不能保证您没有竞争条件,但它可以检测到一些用例.另请注意,您需要引发比赛才能让比赛探测器检测到它,因此必须编写使用您bus同时或模拟真实条件的测试.