doutan3040 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 {
    mutex.Lock()
    if _, exists := sharedMap[k]; exists {
        mutex.Unlock()
        return false
    }
    tokenMap[k] = v
    mutex.Unlock()
    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 ?

  • 写回答

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.

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

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。