无论如何,所有goroutine在执行goroutine时都会睡着

时间:2018-06-05 14:20:03

标签: go udp goroutine

我收到以下错误,我不明白为什么:

Send: Query Herefatal error: all goroutines are asleep - deadlock!

你可以看到im调用我使用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() 
}

1 个答案:

答案 0 :(得分:-5)

尝试

func main(){
 var wg &sync.WaitGroup
 wg.Add(1)
 go routine(wg)
 ...
 wg.Wait()
}
func routine(wg *sync.WaitGroup){
 ...
 defer wg.Done()
}