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[],及偏移量進行計算
Goroutine通信與thread in java間的通信