我收到以下错误,但我不明白为什么:Send: Query Herefatal error: all goroutines are asleep - deadlock!
您可以看到我正在调用使用goroutine创建的函数routine
。我真的没有更多细节可提供。
package main
import (
"fmt"
"net"
"sync"
)
const (
udphost = "127.0.0.1"
udpport = ":150"
StopCharacter = "\r\n\r\n"
)
var wg sync.WaitGroup
func routine() {
defer wg.Done()
// establish connection address parts
schemaUri := udphost + udpport
udpAddr, err := net.ResolveUDPAddr("udp4", schemaUri)
// make connection
conn, err := net.DialUDP("udp", nil, udpAddr)
fmt.Printf("%v", conn)
// defer close
defer conn.Close()
// handle connection errors
if err != nil {
fmt.Println("Erorr Establishing UDP Connection")
return
}
// input query
message := "Query Here"
// Write query to server
conn.Write([]byte(message))
conn.Write([]byte(StopCharacter))
fmt.Printf("Send: %s", message)
// Read response from server
buffr := make([]byte, 1024)
buffw := make([]byte, 1024)
n, _, _, _, _ := conn.ReadMsgUDP(buffr, buffw)
fmt.Printf("Receive: %s", n)
// parse message
msg := string(buffr[0:n])
fmt.Println(msg)
}
func main() {
wg.Add(1)
go routine()
wg.Wait()
}
最佳答案
尝试
func main(){
var wg &sync.WaitGroup
wg.Add(1)
go routine(wg)
...
wg.Wait()
}
func routine(wg *sync.WaitGroup){
...
defer wg.Done()
}
关于go - 无论如何执行goroutine时,所有goroutine都处于 sleep 状态,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50702463/