Goroutine通信与thread in java间的通信

 

 

// This file contains the implementation of Go channels.

 

// Invariants:

//  At least one of c.sendq and c.recvq is empty,

//  except for the case of an unbuffered channel with a single goroutine

//  blocked on it for both sending and receiving using a select statement,

//  in which case the length of c.sendq and c.recvq is limited only by the

//  size of the select statement.

//

// For buffered channels, also:

//  c.qcount > 0 implies that c.recvq is empty.

//  c.qcount < c.dataqsiz implies that c.sendq is empty.

 

import (

    "runtime/internal/atomic"

    "unsafe"

)

  • channel中的数据结构是hchan{}

chan如何初始化:

func makechan(t *chantype, size int) *hchan 

内存分配方式:

不带缓冲区

c = (*hchan)(mallocgc(hchanSize, nil, true))

带缓冲区

c = (*hchan)(mallocgc(hchanSize+uintptr(size)*elem.size, nil, true))

 

—————-

    lock(&c.lock)

 

    if c.closed != 0 {

        unlock(&c.lock)

        panic(plainError("send on closed channel"))

    }

——————

因为chansend中有加锁的步骤,故多个goroutine读写是安全的。

 

 

 

 

PipedInputStream PipedOutputStream 用于在应用程序中创建管道通信。

一个PipedInputStream实例对象必须和一个PipedOutputStream实例对象进行连接而产生一个通信管道。

(必须使用connect,in.connect(out) out.connect(in),效果是等价的)

PipedOutputStream可以向管道中写入数据,PipedIntputStream可以读取PipedOutputStream向管道中写入的数据,这两个类主要用来完成线程之间的通信。

数据从[out,in)范围内读取,并写入到[in,out)范围内

 

 

     { - - - X X X X X X X - - - - - }

             ^             ^

             |             |

            out           in

 

 

     { X X X X - - - - - - - - X X X }

               ^               ^

               |               |

              in              out

 

PipedIntputStream中,缓冲区默认大小是:

private static final int DEFAULT_PIPE_SIZE = 1024;

 

写入数据时:

synchronized void receive(byte b[], int off, int len)  throws IOException

会对byte[],及偏移量进行计算

 

 

原文地址:https://www.cnblogs.com/spillage/p/9121013.html