当运行多个Go应用程序实例时,Gorilla WebSocket连接。

huangapple go评论90阅读模式
英文:

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

http://supervisord.org/

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.

当运行多个Go应用程序实例时,Gorilla WebSocket连接。

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.

huangapple
  • 本文由 发表于 2015年9月18日 18:06:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/32649346.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定