英文:
Gorilla websocket connections when running multiple instances of the Go application
问题
为了保存Gorilla WebSocket连接,我可以像这样使用代码,其中键可以是userId。
connections := make(map[int]*connection)
我正在使用一个叫做supervisord的东西,它是一个进程控制系统,这样我就能够将Go应用程序作为后台守护进程运行。看起来会生成多个实例。
这些实例是否知道如何访问相同的connections变量,如果我将其设为全局变量?
var connections map[int]*connection
还是会有问题吗?
另外,由于map不是线程安全的,我应该创建一个结构体,并在检查键是否存在或从map中删除键之前添加sync.RWMutex
,然后使用RLock()/Lock()和RUnlock()/Unlock()方法吗?
英文:
To save Gorilla websocket connections I could something like this where the key could be a userId.
connections := make(map[int]*connection)
I am using something called supervisord
which is a process control system so that I am able to run the go application
in the background as a daemon. It looks like several instances are being spawned up.
Does those instances know how to access the same connections variable if I make it global?
var connections map[int]*connection
Or will there be an issue?
Also since map is not thread safe, should I create a struct and add sync.RWMutex
and do RLock()/Lock() and RUnlock()/Unlock() before checking whether a key exists or when removing a key from the map?
答案1
得分: 1
首先,那些不是进程,而是线程,所以它们确实会共享相同的全局状态。htop将线程显示为进程。
每当你需要并发访问一个映射时,你需要对其进行同步。你确实可以使用互斥锁来实现这一点。
英文:
First of all, those aren't processes but threads, so they will indeed share the same global state. htop shows threads as if they were processes.
Whenever you need concurrent access to a map, you need to synchronise it. You can indeed do this with a mutex.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论