gpt4 book ai didi

loops - Golang 在带有 channel 的 goroutine 中暂停循环

转载 作者:IT王子 更新时间:2023-10-29 01:49:38 26 4
gpt4 key购买 nike

我有一个作为 goroutine 启动的函数:

func (bt *BlinkyTape) finiteLoop(frames []Frame, repeat int, delay time.Duration) {
bt.isPlaying = true
L:
for i := 0; i < repeat; i++ {
select {
case <-bt.stop:
break L
default:
bt.playFrames(frames, delay)
}
}
bt.isPlaying = false
}

此函数使用 channel ,因此可以打破循环(循环可以是有限的或无限的)

我想实现的是一种暂停循环执行并当然能够恢复它的方法。

我想在选择条件中添加另一个案例,我在另一个 channel pause 上收听。如果案例被执行,它会进入一个什么都不做的新的无限循环。然后,它将需要与以前相同的系统和一个 resume channel 来打破这个循环。

你怎么看?有没有更好的方法来实现我的需要?

问候

最佳答案

在带有 channel 的 goroutine 中暂停循环,使用 playpausequit channel ,就像这个工作示例代码一样:

package main

import "fmt"
import "time"
import "sync"

func routine() {
for {
select {
case <-pause:
fmt.Println("pause")
select {
case <-play:
fmt.Println("play")
case <-quit:
wg.Done()
return
}
case <-quit:
wg.Done()
return
default:
work()
}
}
}

func main() {
wg.Add(1)
go routine()

time.Sleep(1 * time.Second)
pause <- struct{}{}

time.Sleep(1 * time.Second)
play <- struct{}{}

time.Sleep(1 * time.Second)
pause <- struct{}{}

time.Sleep(1 * time.Second)
play <- struct{}{}

time.Sleep(1 * time.Second)
close(quit)

wg.Wait()
fmt.Println("done")
}

func work() {
time.Sleep(250 * time.Millisecond)
i++
fmt.Println(i)
}

var play = make(chan struct{})
var pause = make(chan struct{})
var quit = make(chan struct{})
var wg sync.WaitGroup
var i = 0

输出:

1
2
3
4
pause
play
5
6
7
8
pause
play
9
10
11
12
done

关于loops - Golang 在带有 channel 的 goroutine 中暂停循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38798863/

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