dongtu1958 2016-07-10 04:04
浏览 122
已采纳

在一些不同的goroutine中共享切片

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.

  • 写回答

2条回答 默认 最新

  • doujuan2688 2016-07-10 04:08
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器