启动一个运行递归函数的 goroutine,我想发送一个信号来停止这些递归函数。这就是功能(功能不重要):
func RecursiveFunc(x int, depth int, quit chan bool) int {
if depth == 0 {
return 1
}
if quit != nil {
select {
case <-quit:
return 0
default:
}
}
total := 0
for i := 0; i < x; i++ {
y := RecursiveFunc(x, depth - 1, quit)
if y > 0 {
total += y
}
}
return total
}
这个函数可能需要很长时间才能完成,我想在发送退出信号后停止它并使用结果(无论它是什么)。运行它:
import (
"fmt"
"time"
"sync"
)
func main() {
quit := make(chan bool)
wg := &sync.WaitGroup{}
result := -1
go func() {
defer wg.Done()
wg.Add(1)
result = RecursiveFunc(5, 20, quit)
}()
time.Sleep(10 * time.Millisecond)
close(quit) // Using `quit <- true` doesn't work
wg.Wait()
fmt.Println(result)
}
为了停止 goroutine,我使用一个通道,比如
quit
,关闭它后,程序运行良好,但是我不想真正关闭通道,我只想发送一个信号 quit <- true
。然而,quit <- true
不起作用,我可能只退出一个递归实例。
如何通过发送退出信号来停止递归函数的所有实例?
您可以使用 context 完成您要做的事情。
您可以将一个
context.Context
对象作为第一个参数传递给需要从外部停止的函数,并调用相应的cancel
函数向该函数发送“取消信号”,这将导致Done()
context.Context
的通道将被关闭,因此被调用的函数将在 select
语句中收到取消信号通知。
以下是该函数如何使用
context.Context
处理取消信号:
func RecursiveFunc(ctx context.Context, x int, depth int) int {
if depth == 0 {
return 1
}
select {
case <-ctx.Done():
return 0
default:
}
total := 0
for i := 0; i < x; i++ {
y := RecursiveFunc(ctx, x, depth-1)
if y > 0 {
total += y
}
}
return total
}
以下是如何使用新签名调用该函数:
func main() {
wg := &sync.WaitGroup{}
result := -1
ctx, cancel := context.WithCancel(context.Background())
go func() {
defer wg.Done()
wg.Add(1)
result = RecursiveFunc(ctx, 5, 20)
}()
time.Sleep(10 * time.Millisecond)
cancel()
wg.Wait()
fmt.Println(result)
}
我最近遇到了类似的情况,就像你的情况一样,退出信号被其中一个递归分支消耗,而其他分支没有信号。我通过在从函数返回之前将停止信号转发到通道来解决这个问题。
例如可以将递归函数内部的select修改为:
if quit != nil {
select {
case <-quit:
quit <- true // forward the signal
return 0
default:
}
}
函数递归循环无限使用条件 >= 10 匹配,不要忘记关闭通道并返回
func main() {
x := 1
xChan := make(chan int)
go recursion(x, xChan)
select {
case result := <-xChan:
log.Println("get chan result :", result)
break
}
}
func recursion(i int, xChan chan int) {
if i >= 10 {
xChan <- i
close(xChan)
return
}
a := i + i
log.Println("a :", a)
recursion(a, xChan)
}
尝试添加标志继续执行,但可能不是线程安全的。
var finishIt bool
func RecursiveFunc(x int, depth int, quit chan bool) int {
if finishIt {
return 0
}
//other code here
}
//some code here, but than we decide to stop it
finishIt = true