问题描述
我试图阻止一个去程序,但我找不到一种方法来实现这一点。我正在考虑使用第二频道,但如果我从中读到它会阻止它,不是吗?这里有一些代码,我希望解释我想要做什么。
包主
importfmt
importtime
func main(){
var tooLate bool
proCh:= make(chan字符串)
去func(){
用于{
fmt.Println(working)
//如果tooLate我们停止/返回
if tooLate {
fmt.Println(stopped)
return
}
//处理一些数据并在proCh
上发送结果time.Sleep(2 * time.Second)
proCh< - processed
fmt.Println(done here)
}
}()
select {
case proc:=< -proCh:
fmt.Println(proc)
case< -time.After(1 * time.Second):
//以某种方式发送tooLate< - true
//以便我们可以停止执行
fmt.Println(太迟)的去程序
}
time.Sleep(4 * time.Second)
fmt.Println(finish \\\
)
}
有几种方法可以实现,最简单也最方便的是使用另一个通道: (){
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ chan string)
去func(){
for {
fmt.Println(working)
time.Sleep(1 * time.Second)
select {
case< -tooLate:
fmt.Println(stopped)
return
case proCh< - processed:// This why it won如果计时器过期,不会阻止goroutine。
default://添加默认值将使其不会阻止
}
fmt.Println(done here)
}
}()
select {
case proc:=< -proCh:
fmt.Println(proc)
case< -time.After(1 * time.Second):$ b $ (太晚了)
关闭(tooLate)
}
time.Sleep(4 * time.Second)
fmt.Println( finish'\
)
}
$ b
您也可以使用
I'm trying to stop a go routine but I can't find a way to achieve this. I was thinking to use a 2nd channel but if I read from that it would block it isn't it ?. Here is some code which I hope explains what I'm trying to do.
package main
import "fmt"
import "time"
func main() {
var tooLate bool
proCh := make(chan string)
go func() {
for {
fmt.Println("working")
//if is tooLate we stop/return it
if tooLate {
fmt.Println("stopped")
return
}
//processing some data and send the result on proCh
time.Sleep(2 * time.Second)
proCh <- "processed"
fmt.Println("done here")
}
}()
select {
case proc := <-proCh:
fmt.Println(proc)
case <-time.After(1 * time.Second):
// somehow send tooLate <- true
//so that we can stop the go routine running
fmt.Println("too late")
}
time.Sleep(4 * time.Second)
fmt.Println("finish\n")
}
There are few ways to achive that, the easiest and most convenient is using another channel like:
func main() {
tooLate := make(chan struct{})
proCh := make(chan string)
go func() {
for {
fmt.Println("working")
time.Sleep(1 * time.Second)
select {
case <-tooLate:
fmt.Println("stopped")
return
case proCh <- "processed": //this why it won't block the goroutine if the timer expirerd.
default: // adding default will make it not block
}
fmt.Println("done here")
}
}()
select {
case proc := <-proCh:
fmt.Println(proc)
case <-time.After(1 * time.Second):
fmt.Println("too late")
close(tooLate)
}
time.Sleep(4 * time.Second)
fmt.Println("finish\n")
}
You can also look into using sync.Cond
这篇关于如何通知goroutine停止跑步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!