Goroutine通訊與thread in java間的通訊

來源:互聯網
上載者:User

標籤:大小   contain   intern   malloc   throw   select   goroutine   out   ffffff   

 

 

// 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間的通訊

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.