2 回答

TA貢獻1808條經(jīng)驗 獲得超4個贊
聽起來你需要在 goroutines 之間進行同步,也許沿著這條線。
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)
}
這篇文章非常清楚地解釋了使用通道和同步組進行同步。

TA貢獻1887條經(jīng)驗 獲得超5個贊
這就是我最終作為我的 debouncer 實現(xiàn)的:
func Debounce(lull time.Duration, in chan struct{}, out chan struct{}) {
go func() {
var last int64 = 0
for {
select {
case <-in:
last = time.Now().Unix()
case <-time.Tick(lull):
if last != 0 && time.Now().Unix() >= last+int64(lull.Seconds()) {
last = 0
out <- struct{}{}
}
}
}
}()
}
它需要一個間歇時間,即如果我們沒有收到輸入的持續(xù)時間,那么我們假設(shè)數(shù)據(jù)突發(fā)中存在中斷。有2個通道,1個輸入和1個輸出。數(shù)據(jù)突發(fā)到達輸入端,對于每個突發(fā),我們在突發(fā)結(jié)束時寫入輸出通道。
實現(xiàn)非常簡單。每次從輸入通道接收時,我只存儲當前的 unix 時間戳。然后,我有一個停頓時間的自動收報機。所有這些都是檢查我們是否已經(jīng)超過了最后一次突發(fā)的等待時間。如果是這樣,它會重置last為 0,并在輸出通道上發(fā)出一個事件。
下面是一些使用 debounce 函數(shù)的代碼,它的靜止時間為 2 秒,它在輸入通道上發(fā)送隨機突發(fā):
func main() {
out := make(chan struct{})
in := make(chan struct{})
Debounce(2*time.Second, in, out)
// Generating bursts of input data
go func(in chan struct{}) {
for {
select {
case <-time.Tick(1 * time.Second):
in <- struct{}{}
fmt.Println("Sending!")
shouldSleep := rand.Intn(2)
if shouldSleep == 1 {
time.Sleep(5 * time.Second)
}
}
}
}(in)
// Listening for output events
go func(out chan struct{}) {
for _ = range out {
fmt.Println("Got an event!")
}
}(out)
// Do not let main terminate.
done := make(chan struct{})
<-done
}
- 2 回答
- 0 關(guān)注
- 173 瀏覽
添加回答
舉報