Golang Goroutine实践,功能还是渠道?
不断从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经常遇到错误,通常是“致命错误:运行时执行期间的意外信号”。
go processJson(message)
从我的理解来看,两个goroutine都可以做到这一点,为什么第一个可以运行良好,第二个不能。我尝试使用频道,但与第一个Goroutine相比,没有太大的区别。
msgChan := make(chan string, 1000)
go processJson(msgChan)
for { //receive json from websocket, send to channel
msgChan <- message
}
func JsonProcessor(msg chan string) {
for { //get data from channel, process in goroutine function
msgModified := <-msg
insertDatabase(msgModified)
}
}
如果没有数据竞赛,是否有任何鼓励的方法来实现目标,欢迎提出建议。 感谢,谢谢。
constantly receive Json data from websocket and process them in goroutine, no idea is this writing pattern is encourage or not
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
}
Below(the first goroutine) work just fine, but sometime(a week) indicates there is a data race in the code and terminate the program.
go func() {
defer processJson(message)
}()
the second goroutine, often encounter error after few minutes running, the error often is "fatal error: unexpected signal during runtime execution".
go processJson(message)
from my understanding both goroutine do the samething, why is that the first can run well and second cannot. i have try using channel, but not much difference compare to the first goroutine.
msgChan := make(chan string, 1000)
go processJson(msgChan)
for { //receive json from websocket, send to channel
msgChan <- message
}
func JsonProcessor(msg chan string) {
for { //get data from channel, process in goroutine function
msgModified := <-msg
insertDatabase(msgModified)
}
}
is there any encourage way to acheive the goal without data race, suggestions are welcome.
Appreciate and Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试使用
sync.mutex
避免使用数据赛车,如果可以在没有数据赛车的情况下进行处理功能,请按以下方式进行多线程版本:
try to use
sync.Mutex
avoid data racingif the processing function can be divided without data racing, multithread version as follows :