chan通道无阻塞读写

通过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)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。