在Go语言中,tls.Conn是否是“goroutine安全”的?

huangapple go评论66阅读模式
英文:

is the tls.Conn "goroutine safe" in golang?

问题

我有一个问题:
在一个goroutine中,我可以同时使用tls.read读取tls连接,而另一个goroutine正在调用tls.write吗?
代码可能如下所示:

func main() {
    tlsConn := tls.Conn
    go func() {
        tlsConn.read(...)
    }()
    go func() {
        tlsConn.write(...)
    }()
}
英文:

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(...)
        }()
}

答案1

得分: 4

tls的读取和写入是相互独立的。

读取和写入分别使用不同的互斥锁。

源代码片段如下:

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 {
        // 在 Handshake 之后放置此代码,以防止人们对 Read(nil) 进行调用以达到 Handshake 的副作用。
        return
    }
    
    c.in.Lock()
    defer c.in.Unlock()
    .
    .
}

因此:

  1. 您可以同时进行写入和读取操作。

  2. 您可以同时进行多个读取操作,但一次只能进行一次读取。

  3. 您可以同时进行多个写入操作,但一次只能进行一次写入。

英文:

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

  1. You can write and read concurrently.

  2. You can do multiple read concurrently but only one read will happen at a time.

  3. You can do multiple write concurrently but only one write will happen at a time.

答案2

得分: 3

输入和输出是分离的,因此它们不应该相互干扰。对WriteRead的并发调用受到互斥锁的保护。

因此,是的,它们可以安全地以并发方式调用。

英文:

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.

huangapple
  • 本文由 发表于 2015年8月14日 18:16:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/32007671.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定