douzhuan1169 2016-07-17 02:13
浏览 144

如何在Golang中正确处理缓冲通道?

I have a channel which stores received data, I want to process it when one of following conditions is met:
1, the channel reaches its capacity.
2, the timer is fired since last process.

I saw the post Golang - How to know a buffered channel is full

Update:

I inspired from that post and OneOfOne's advice, here is the play :

package main

import (
    "fmt"
    "math/rand"
    "time"
)

var c chan int
var timer *time.Timer

const (
    capacity     = 5
    timerDration = 3
)

func main() {
    c = make(chan int, capacity)
    timer = time.NewTimer(time.Second * timerDration)
    go checkTimer()
    go sendRecords("A")
    go sendRecords("B")
    go sendRecords("C")

    time.Sleep(time.Second * 20)
}

func sendRecords(name string) {
    for i := 0; i < 20; i++ {
        fmt.Println(name+" sending record....", i)
        sendOneRecord(i)
        interval := time.Duration(rand.Intn(500))
        time.Sleep(time.Millisecond * interval)
    }
}

func sendOneRecord(record int) {
    select {
    case c <- record:
    default:
        fmt.Println("channel is full !!!")
        process()
        c <- record
        timer.Reset(time.Second * timerDration)
    }
}

func checkTimer() {
    for {
        select {
        case <-timer.C:
            fmt.Println("3s timer ----------")
            process()
            timer.Reset(time.Second * timerDration)
        }
    }
}

func process() {
    for i := 0; i < capacity; i++ {
        fmt.Println("process......", <-c)
    }
}

This seems to work fine, but I have a concern, I want to block the channel writing from other goroutine when process() is called, is the code above capable to do so? Or should I add a mutex at the beginning of the process method?

Any elegant solution?

  • 写回答

2条回答

  • duanhoupeng6642 2016-07-17 02:41
    关注

    No, select is the only way to do it:

    func (t *T) Send(v *Val) {
        select {
        case t.ch <- v:
        default:
            // handle v directly
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥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,如何解決?