美文网首页
chan通道无阻塞读写

chan通道无阻塞读写

作者: 柯蓝_e007 | 来源:发表于2019-05-07 09:49 被阅读0次

    通过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)
    

    相关文章

      网友评论

          本文标题:chan通道无阻塞读写

          本文链接:https://www.haomeiwen.com/subject/vybsoqtx.html