• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Spillage
博客园    首页    新随笔    联系   管理    订阅  订阅
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[],及偏移量进行计算

 

 

posted on 2018-06-01 11:56  Spillage  阅读(153)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3