【问题标题】:golang goroutine practice, function or channal?golang goroutine 实践,function 还是 channal?
【发布时间】: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


【解决方案1】:

尽量使用sync.Mutex 避免数据竞速

mutux := sync.Mutex
ws.onmessage {
  processJson(message)
}
func processJson(msg string) {
  mutux.Lock()
  // .........
  mutux.Unlock()
}

如果处理功能可以不进行数据竞速划分,多线程版本如图:

msgChan1 := make(chan string)
msgChan2 := make(chan string)

go func() {
  for m := range msgChan1 {
    // ...
  }
}()
go func() {
  for m := range msgChan2 {
    // ...
  }
}()

ws.onmessage {
  msgChan1 <- message
  msgChan2 <- message
}
ws.onclose {
  close(msgChan1)
  close(msgChan2)
}

【讨论】:

    猜你喜欢
    • 2015-12-07
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多