并发映射是否应该被 goroutine 和通道机制所取代?

huangapple go评论66阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2016年1月6日 19:04:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/34631561.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定