【发布时间】:2022-06-10 20:16:32
【问题描述】:
不断从 websocket 接收 Json 数据并在 goroutine 中处理它们,不知道这种写作模式是否鼓励
ws.onmessage { //infinite receive message from websocket
go func() { //work find using this goroutine
defer processJson(message)
}()
go processJson(message) //error and program will terminated
}
func processJson(msg string) {
//code for process json
insertDatabase(processedMsg)
}
func insertDatabase(processedMsg string) {
//code insert to database
}
以下(第一个 goroutine)工作正常,但有时(一周)表明代码中存在数据竞争并终止程序。
go func() {
defer processJson(message)
}()
第二个goroutine,运行几分钟后经常遇到错误,错误经常是“fatal error: unexpected signal during runtime execution”。
go processJson(message)
据我了解,两个 goroutine 都做同样的事情,为什么第一个可以运行良好而第二个不能。我尝试过使用通道,但与第一个 goroutine 相比没有太大区别。
msgChan := make(chan string, 1000)
go processJson(msgChan)
for { //receive json from websocket, send to channal
msgChan <- message
}
func JsonProcessor(msg chan string) {
for { //get data from channel, process in goroutine function
msgModified := <-msg
insertDatabase(msgModified)
}
}
是否有任何鼓励的方式来实现没有数据竞赛的目标,欢迎提出建议。 感谢并感谢。
【问题讨论】:
-
go processJson(message)和流代码go func(msg string) { defer processJson(msg)}(message)做同样的事情,也许是bug
标签: go websocket concurrency channel goroutine