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

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.

图片转代码服务由CSDN问答提供 功能建议

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

  var(
 bus * Bus //此变量
)
 
 // Bus代表存储库总线。  
type总线结构{
 UserRepository * UserRepository 
 // ... 
} 
   
 
 

... 访问我的存储库中的 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”))))
} \  n 
 // Service 
func(s UserService)FindUser(id int)* domain.User {
 return s.UserRepository.FindByID(id)
} 
 
 // Repository 
func(r UserRepository)FindByID  (id int)* domain.User {
 //这是使用包范围的`bus`变量的地方
} 
   
 
 

在< code> FindByID 函数,我可以使用包范围的 bus 变量,当然可以同时访问 ce只要HTTP请求触发它就会被调用,并且所有这些请求都会同时处理。

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

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.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题