gpt4 book ai didi

go - 我如何等待 channel 事件的间歇来触发某些事情?

转载 作者:数据小太阳 更新时间:2023-10-29 03:15:55 25 4
gpt4 key购买 nike

我有一个 channel ,它将接收对它的突发写入。我想等到 channel 上的突发发送完成后再触发操作。

我看过这个gist , 但是,如果缓冲区中有数据,它将每隔 interval 发送一次输出:

func debounceChannel(interval time.Duration, output chan int) chan int {
input := make(chan int)

go func() {
var buffer int
var ok bool

// We do not start waiting for interval until called at least once
buffer, ok = <-input
// If channel closed exit, we could also close output
if !ok {
return
}

// We start waiting for an interval
for {
select {
case buffer, ok = <-input:
// If channel closed exit, we could also close output
if !ok {
return
}

case <-time.After(interval):
// Interval has passed and we have data, so send it
output <- buffer
// Wait for data again before starting waiting for an interval
buffer, ok = <-input
if !ok {
return
}
// If channel is not closed we have more data and start waiting for interval
}
}
}()

return input
}

在我的例子中,我想等到输入 channel 上不再有任何数据在触发或发送输出之前发送到此突发。

我如何实现这一目标?

最佳答案

听起来您需要在 goroutine 之间进行同步,也许沿着这条线。

func main() {

// Create a channel for our input
input := make(chan int, 1)
// Create another for synchronization between main and forked goroutines
done := make(chan bool)

go func() {
// block-wait for received value
<-input

// do some more things here

// when done, send signal to the main goroutine
done <- true
}()

// Do something while wait for the forked goroutine

// this block until `<-done`
<-done
close(mychan)
}

post非常清楚地解释了使用 channel 和同步组进行同步。

关于go - 我如何等待 channel 事件的间歇来触发某些事情?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35979863/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com