Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are golang net.UDPConn and net.TCPConn thread safe?? Can i read or write of single UDPConn object in multi thread?

1.Can we call send from one thread and recv from another on the same net.UDPConn or net.TCPConn objects?

2.Can we call multiple sends parallely from different threads on the same net.UDPConn or net.TCPConn objects?

I am unable to find a good documentation also for the same. Is golang socket api thread safe?

I find that it is hard to test if it is thread safe. Any pointers in the direction will be helpful.

My test code is below:

package main

import (
    "fmt"
    "net"
    "sync"
)

func udp_server() {
    // create listen
    conn, err := net.ListenUDP("udp", &net.UDPAddr{
        IP:   net.IPv4(0, 0, 0, 0),
        Port: 8080,
    })
    if err != nil {
        fmt.Println("listen fail", err)
        return
    }
    defer conn.Close()

    var wg sync.WaitGroup
    for i := 0; i < 10; i = i + 1 {
        wg.Add(1)
        go func(socket *net.UDPConn) {
            defer wg.Done()
            for {
                // read data
                data := make([]byte, 4096)
                read, remoteAddr, err := socket.ReadFromUDP(data)
                if err != nil {
                    fmt.Println("read data fail!", err)
                    continue
                }
                fmt.Println(read, remoteAddr)
                fmt.Printf("%s\n\n", data)

                // send data
                senddata := []byte("hello client!")
                _, err = socket.WriteToUDP(senddata, remoteAddr)
                if err != nil {
                    return
                    fmt.Println("send data fail!", err)
                }
            }
        }(conn)
    }
    wg.Wait()
}

func main() {
    udp_server()
}

Is it OK for this test code?

like image 838
习明昊 Avatar asked Feb 18 '15 04:02

习明昊


1 Answers

The documentation for net.Conn says:

Multiple goroutines may invoke methods on a Conn simultaneously.

like image 189
thwd Avatar answered Oct 14 '22 07:10

thwd