0

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 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

The map implementation that I've mentioned does exactly the same - a regular map with a RWMutex. But what can you say about channels vs. thread-safe containers in general? Thanks for your answer!
The map implementations you mentioned tries to be more scalable by splitting the keys into multiple shards and using a single RWMutex per shard. It is not very clear if the goal has been achieved though, there are no benchmarks showing that it scales better under concurrent access.
channels, locks, atomic variables, thread-safe collections are just tools to achieve your goals. There are use cases for all of them, depending on your requirements. And remember that sometimes a single-threaded program is the fastest ;)
Thank you for your time, you're being very helpful, and I indeed should pay more attention to the code I show people :) but can you please in sake of additional clarification highlight a few cases where channels are at their best?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.