英文:
Should goroutine/channel-based mechanism replace a concurrent map?
问题
有一个map[PlayerId]Player
用于检查玩家是否在线并根据其ID执行状态更改。这必须从多个goroutine同时进行。
目前,我计划使用streamrail的concurrent map,但是使用常规的map和使用通道进行同步呢?
- 在Go中,它应该始终被优先考虑吗?
- 在某些情况下,它应该被优先考虑吗?
- 它们基本上只是实现相同目标的两种方式吗?
顺便说一下,我知道这个口号:
> 不要通过共享内存来通信,而要通过通信来共享内存
但是stdlib中有锁机制,并且文档中没有提到完全不使用它们。
英文:
There's a map[PlayerId]Player
to check whether player is online and perform state alterations knowing his ID. This must be done from multiple goroutines concurrently.
For now I plan to use streamrail's concurrent map, but what about a regular map and synchronization using channels?
- Should it always be preferred in Go?
- Should it be preferred in certain circumstances?
- Are they basically just two ways to accomplish the same thing?
BTW, I know the slogan:
> don't communicate by sharing memory share memory by communicating
but there are locking mechanisms in stdlib and no words in docs about not using them at all.
答案1
得分: 1
从最简单的方法开始:使用地图和RWMutex。
我不建议使用并发库,除非它被广泛使用和测试(例如,请参阅https://github.com/streamrail/concurrent-map/issues/6)。
请注意,即使您使用github.com/streamrail/concurrent-map,在以下场景中仍需要实现自己的同步(使用RWMutex):
if _, ok = m[k]; !ok {
m[k] = newPlayer()
}
如果您的游戏非常受欢迎并且有很多玩家,您会发现这种方法无法扩展,但只有在它成为问题时才需要担心。
英文:
Start with the simplest approach: a map and RWMutex.
I cannot recommend using concurrency library unless it is widely used and tested (see https://github.com/streamrail/concurrent-map/issues/6 for example).
Note that even if you use github.com/streamrail/concurrent-map you will still need to implement your own synhronisation (use RWMutex) in the following scenario:
if _, ok = m[k]; !ok {
m[k] = newPlayer()
}
If your game is super popular and played by many players you will find that this approach doesn't scale but I would worry about it only if it becomes a problem.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论