doujumiao5024 2017-08-31 15:52
浏览 253
已采纳

io.Pipe Write()和Read()函数如何工作?

By reading golang src pipe.go to figure out how pipe works, I ran into these two write() & read() functions. What confuses me is that if reader calls read() func and hold l.lock and then waiting for data, how does writer call write() func and acquire l.lock to write data in?

func (p *pipe) write(b []byte) (n int, err error) {
    // pipe uses nil to mean not available
    if b == nil {
        b = zero[:]
    }

    // One writer at a time.
    p.wl.Lock()
    defer p.wl.Unlock()

    p.l.Lock()
    defer p.l.Unlock()
    if p.werr != nil {
        err = ErrClosedPipe
        return
    }
    p.data = b
    p.rwait.Signal()
    for {
        if p.data == nil {
            break
        }
        if p.rerr != nil {
            err = p.rerr
            break
        }
        if p.werr != nil {
            err = ErrClosedPipe
            break
        }
        p.wwait.Wait()
    }
    n = len(b) - len(p.data)
    p.data = nil // in case of rerr or werr
    return
}

and read:

func (p *pipe) read(b []byte) (n int, err error) {

    // One reader at a time.
    p.rl.Lock()
    defer p.rl.Unlock()

    p.l.Lock()
    defer p.l.Unlock()
    for {
        if p.rerr != nil {
            return 0, ErrClosedPipe
        }
        if p.data != nil {
            break
        }
        if p.werr != nil {
            return 0, p.werr
        }
        p.rwait.Wait()
    }
    n = copy(b, p.data)
    p.data = p.data[n:]
    if len(p.data) == 0 {
        p.data = nil
        p.wwait.Signal()
    }
    return
}
  • 写回答

1条回答 默认 最新

  • duanhuang2150 2017-08-31 16:03
    关注

    The mutex p.l is used in the read and write sync.Cond conditions, which will lock and unlock it as necessary.

    Calling Wait on the condition unlocks its lock, and waits for a corresponding Signal call. You can see that the pipe uses p.wwait and p.rwait to coordinate the readers and writers within the Read and Write methods.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog