基于goroutine / channel的机制应该取代并发映射吗? [英] Should goroutine/channel-based mechanism replace a concurrent map?

查看:78
本文介绍了基于goroutine / channel的机制应该取代并发映射吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个 map [PlayerId] Player 来检查玩家是否在线,并知道他的ID是否进行状态改变。这必须同时从多个goroutines完成。



现在我打算使用 streamrail的并发映射,但是如何使用频道定期映射和同步?


  • 在Go中是首选吗?

  • 在某些情况下它应该是首选吗?

  • 他们基本上只是两种方法来完成相同的事情吗?
  • >


顺便说一句,我知道这个口号:


don通过沟通共享内存共享内存进行通信


但stdlib中有锁定机制,文档中没有关于不使用它们的文字all。

解决方案

从最简单的方法开始:一张地图和一张RWMutex。

我不推荐使用并发库,除非它被广泛使用和测试(参见 https://github.com/streamrail/concurrent-map/issues/6 )。



请注意,即使您使用github.com/streamrail/concurrent-map,您仍然需要在以下情况下实施自己的synhronisation(使用RWMutex):

  if _,ok = m [k]; !ok {
m [k] = newPlayer()
}

游戏是超级流行的,并且由许多玩家发挥,你会发现这种方法不会扩展,但只有在它成为问题时我才会担心。


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.

解决方案

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.

这篇关于基于goroutine / channel的机制应该取代并发映射吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆