如何在goroutine中实现暂停和恢复处理功能?
时间:2024-02-25
浏览:468
作者:佚名
最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《如何在goroutine中实现暂停和恢复处理功能?》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~
问题内容
所以我有这个小型控制台应用程序,我在其中启动一个仅输出递增数字的 goroutine。
我可以告诉它 start 和 stop 并且这些命令工作正常。
我将如何实现 pause 和 resume 命令,我不确定如何在我的频道中传递此信息,我可以更改频道以接受 string 或 integer 但不确定如何实际执行暂停? p>
func main() {
fmt.Println("starting...")
reader := bufio.NewReader(os.Stdin)
quit := make(chan bool)
last := 1
for {
text, _ := reader.ReadString('\n')
text = strings.Replace(text, "\n", "", -1)
fmt.Printf("entered: %s\n", text)
switch {
case text == "start":
fmt.Println("starting")
go counter(last, 1, quit, &last)
case text == "pause":
fmt.Println("pausing")
case text == "resume":
fmt.Println("resuming")
case text == "stop":
fmt.Println("stopping")
quit <- true
}
fmt.Printf("last is %v", last)
}
}
func counter(startFrom int, multiplyBy int, quit <-chan bool, last *int) {
for {
for x := startFrom; x < 100; x++ {
time.Sleep(time.Millisecond * 1000)
select {
case <-quit:
fmt.Printf("counter stopped")
return
default:
result := x * multiplyBy
*last = result
fmt.Printf("%d", result)
}
}
}
}正确答案
您可以引入第二个通道,然后将其用于暂停/恢复。
这样的事情应该有效:
func counter(startFrom int, multiplyBy int, quit, pause <-chan bool, last *int) {
for {
for x := startFrom; x < 100; x++ {
time.Sleep(time.Millisecond * 1000)
select {
case <-quit:
fmt.Printf("counter stopped")
return
case msg := <-pause:
if msg == true {
fmt.Printf("counter paused")
pause_loop:
for {
select {
case msg := <-pause:
if msg == false {
fmt.Printf("counter resumed")
break pause_loop
}
case <-quit:
fmt.Printf("counter stopped")
return
}
}
}
default:
result := x * multiplyBy
*last = result
fmt.Printf("%d", result)
}
}
}
}
终于介绍完啦!小伙伴们,这篇关于《如何在goroutine中实现暂停和恢复处理功能?》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.29
11.29
11.29
11.29
11.29
11.29
11.29
热门专题
