2017-05-31 21:28
浏览 69


So currently I've come upon a very real problem in writing "correct" golang. I have an object (for the sake of simplicity lets think of it as a map[string]string) and I want it to hold a "shared" state between multiple gortuines.

Currently the implementation goes something like this:

//Inside shared_state.go

var sharedMap    map[string]string = make(map[string]string)
var mutex       sync.RWMutex     = sync.RWMutex{}

func Add(k string, v string) bool {
    if _, exists := sharedMap[k]; exists {
        return false
    tokenMap[k] = v
    return true
//Other methods to access, modify... etc

Whilst this does do the job is quite an ugly implementation by go standards, which encourage modeling concurrency using message.

Are there easy ways of modeling shared state using messages that I am blatantly unaware of ? Or am I forced to use mutexes in this kind of cases ?

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

因此,目前我在编写“正确的” golang时遇到了一个非常现实的问题。 我有一个对象(为简单起见,我们将其视为map [string] string),并且我希望它在多个gortuine之间保持“共享”状态。

当前 实现过程如下:

  // Inside shared_state.go 
var sharedMap map [string] string = make(map [string] string)
var互斥体同步。  RWMutex = sync.RWMutex {} 
func Add(k字符串,v字符串)bool {
如果_,则存在:= sharedMap [k]; 存在{
 tokenMap [k] = v 
 //其他访问,修改方法。  .etc 


是否有使用我公然不知道的消息对共享状态进行建模的简便方法? 还是我不得不在这种情况下使用互斥锁?

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

1条回答 默认 最新

  • doulachan8217 2017-06-01 14:12

    You don't "model shared state using messages", you use messages instead of shared state, which requires designing the application based on different fundamentals. It is generally not a matter of rewriting a mutex as a channel, but a completely different implementation approach, and that approach won't be applicable to all scenarios where you need to synchronize operations. If a shared map is the best approach for your situation, then a mutex is the correct way to synchronize access to it.

    As an example from my own experience, I've developed applications that allow for changing their configuration at runtime. Rather than having a shared Config object and synchronizing access to it, I give each main goroutine a channel on which it can receive configuration updates. When the config changes, the update is sent to all the listeners. When a listener gets a config change, it can complete its current operation, then deal with the config change in whatever way is appropriate to that routine - it may just update its local copy of the config, it may close connections to external resources and open new ones, etc. Instead of sharing data, I'm sending and receiving events, which is a fundamentally different design.

    解决 无用
    打赏 举报

相关推荐 更多相似问题