I have a question: Can I tls.read a tls connection in one goroutine, while the other goroutine is calling tls.write? the code may like this:
func main() {
tlsConn := tls.Conn
go func() {
tlsConn.read(...)
}()
go func() {
tlsConn.write(...)
}()
}
Input and output are separated so they should not interfere. Concurrent calls to either Write
or Read
are guarded by a mutex lock.
Therefore, yes they are safe to be called in a concurrent manner.
tls Read and write are independent of each other.
Read and Write uses seperate mutex in and out respectedly.
Snippet from the source code
func (c *Conn) Write(b []byte) (int, error) {
if err := c.Handshake(); err != nil {
return 0, err
}
c.out.Lock()
defer c.out.Unlock()
.
.
}
func (c *Conn) Read(b []byte) (int, error) {
if err := c.Handshake(); err != nil {
return 0, err
}
if len(b) == 0 {
// Put this after Handshake, in case people were calling
// Read(nil) for the side effect of the Handshake.
return
}
c.in.Lock()
defer c.in.Unlock()
.
.
}
Thus
You can write and read concurrently.
You can do multiple read concurrently but only one read will happen at a time.
You can do multiple write concurrently but only one write will happen at a time.