chan通道无阻塞读写

2019-05-07  本文已影响0人  柯蓝_e007

通过time超时机制实现


func ReadWithTimeout(ch chan []byte, timeoutMs time.Duration) (ret []byte, err error) {

    timeout := time.NewTimer(time.Millisecond * timeoutMs)

    select {
    case ret = <- ch:
        return ret, nil
    case <- timeout.C:
        return nil, errors.New("timeout")
    default:
        return nil, errors.New("unkonw")
    }

}

func WriteWithTimeout(ch chan []byte, data []byte, timeoutMs time.Duration) error {

    timeout := time.NewTimer(time.Millisecond * timeoutMs)

    select {
    case ch <- data:
        return nil
    case <-timeout.C:
        return errors.New("timeout")
    default:
        return errors.New("unkonw")
    }
}

使用如下:

readChannel= make(chan []byte, 4096);//创建一个带4k缓存的字节数据通道
data ,err := ReadWithTimeout(readChannel,50)

writeChannel= make(chan []byte, 4096);
WriteWithTimeout(writeChannel,data ,50)
上一篇 下一篇

猜你喜欢

热点阅读