dpbf62565 2017-11-04 04:57
浏览 43
已采纳

更新未读频道数据

Is there a way to update unread data that been sent to a channel with more up to date data?

I have a goroutine (producer) with a channel that's provides progress updates to another goroutine (consumer). In some scenarios, the progress can update much faster than the consumer consumes the update messages.

This causes me issues as I can either:

  • Block on sending data to the channel. This means that if the consumer is slow to read data, the progress updating goroutine totally blocks - which it shouldn't.
  • Don't block on sending and skip over progress updates when the channel is full. This means the consumer is always reading old, out of data data.

As an example, I might have something like this:

Progress reporting goroutine: Posts "1%" to channel Progress reporting goroutine: Posts "2%" to channel Progress reporting goroutine: Posts "3%" to channel Progress consuming goroutine: Reads "1%", "2%" and "3%" from channel. "1% and "2%" are outdated information.

Is there any way to update unread channel data? Or is there a better way of going about this issue?

  • 写回答

4条回答 默认 最新

  • dsgwoh7038 2017-11-04 05:12
    关注

    You can store some value in a global variable protected with RWMutex It keeps progress. Generator updates it. Consumer reads and shows.

    Also you can make a non-blocking writing to channel with length of 1:

    var c = make(chan struct{}, 1)
    select {
    case c <- struct{}{}:
    default:
    }
    

    This way sender either adds one element to the channel either do nothing if it’s full.

    Reader treats this empty struct as a signal - it should take updated value in the global variable.

    Another way: Updatable channel

    var c = make(chan int, 1)
    select {
    case c <- value:  // channel was empty - ok
    
    default: // channel if full - we have to delete a value from it with some precautions to not get locked in our own channel
        switch {
        case <- c: // read stale value and put a fresh one
             c <- value
        default: // consumer have read it - so skip and not get locked
         }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。