Sharing a slice across a few different goroutines

Issue

Given that I have an slice of structs of type User

Users := make([]User)

I am listening for TCP connections, and when a user connects, I’m adding an new user to this slice.

The way I’ve done this, is by setting up a NewUsers channel

NewUsers := make(chan User)

Upon new TCP connects, a User gets sent to this channel, and a central function waits for a User to arrive to add it to the Users slice.

But now I would like multiple subsystems (packages/functions) to use this list of Users. One function might simply want to receive a list of users, while a different function might want to broadcast messages to every user, or just users matching a certain condition.

How do multiple functions (which are possibly executed from different goroutines) safely access the list of users. I see two possible ways:

  1. Every subsystem that needs access to this list needs their own AddUser channel and maintain their own slice of users and something needs to broadcast new users to every one of these channels.
  2. Block access with a Mutex

Option 1 seems very convoluted and would generate a fair bit of duplication, but my understanding that Mutexes are best to be avoided if you try to stick to the “Share Memory By Communicating” mantra.

Solution

The mutex approach is the best, safest and most manageable approach to that problem and is the fastest.

Channels are complex beasts on the inside and are much slower than a rwmutex-guarded map/slice.

Answered By – OneOfOne

Answer Checked By – Pedro (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.