英文:
Update a global variable every 180 seconds without sleeping or blocking the client
问题
我正在编写一个P2P协议中的对等体。我有一个表示我想要通信的对等体的地图的全局变量。然而,我希望每隔180秒更新一次这个地图,而不会阻塞客户端,因为我仍然需要能够发送数据包和处理接收到的数据包。
到目前为止,客户端的结构类似于以下代码:
var peers map[int]Peer
func main() {
for {
// 每隔180秒更新对等体地图
// 发送数据包/接收数据包
}
}
问题出在定时更新上。我已经进行了一些搜索,发现很多可能的解决方案使用了time.AfterFunc
或者Sleep
。但是我对AfterFunc
的行为不确定,因为它是一个Goroutine,据我了解,只有全局变量的副本被传递给Goroutine,对吗?所以这可能不是一个可行的解决方案,或者我可能误解了底层概念。
我认为可能有一个非常简单的解决方案,但我自己想不出来。我很乐意阅读一些可能的解决方案。
谢谢!
英文:
I'm a writing a peer in a P2P protocol. I have a global variable representing a map of the peers I want to communicate with. However, I want to update this map every 180 seconds without sleeping or blocking the client because I still need to be able to send packets and process the ones incoming.
The structure of the client so far ressembles to something like this:
var map[int]Peer
func main() {
for {
// Every 180 seconds, update peers map
// send packets / receive packets
}
}
The problematic part is the timed update. I've made searches and a lot of the possible solutions uses time.AfterFunc
or a Sleep
. But I'm unsure about the behaviour of AfterFunc
considering it's a Goroutine and as far as I understand, only a copy of the global variables are passed to the Goroutines right? So it may not a viable solution, or maybe I misunderstood the underlying concepts.
I think there might a very simple solution I'm not able to come up with. I'd be glad to read some possible solutions to this problem.
Thanks
答案1
得分: 1
只有全局变量的副本被传递给 Goroutines 吗?
不,一个 Goroutine 可以修改全局变量。但是如果你这样做,要特别注意数据竞争。你可能需要添加一个互斥锁来保护对全局变量的并发访问。
英文:
> only a copy of the global variables are passed to the Goroutines right?
No, a goroutine can mutate a global variable. But if you do it this way, pay extra attention to data races. You might want to add a mutex to protect concurrent access of the global variable.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论