据我所知,上下文库的主要目的是停止执行所有子‘s RPC和HTTP请求。或者用简单的语言,我们可以说,在上下文库的帮助下,我们可以将触发器传递给函数调用。
这是我想用上下文解决的抽象问题形式。
package main
import (
"context"
"fmt"
"time"
)
func PrintAndStop(ctx context.Context, numberOfTimePrint int, msg string) {
communicationChannel := make(chan bool)
go func() {
for i := 0; i < numberOfTimePrint; i++ {
fmt.Println(msg)
time.Sleep(time.Second)
}
communicationChannel <- true
}()
select {
case <-communicationChannel:
fmt.Println("process has been completed")
case <-ctx.Done():
fmt.Println("closing call from the main function")
}
}
func main() {
ctx := context.Background()
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
PrintAndStop(ctx, 5*time.Second, "testing")
time.Sleep(5 * time.Second)
}以下代码的输出如下:
testing
testing
testing
closing call from the main function
testing
testing这里提供了以下代码片段的链接:https://play.golang.org/p/4Ntwn3wYOiT PrintAndStop是一种方法,它以1秒的间隔打印某些消息,每次给定次数。在上下文库的帮助下,我希望控制主函数,以便随时停止PrintAndStop的执行。main末尾的time.Sleep(5 * time.Second)只是主函数在函数调用后没有结束的表示。
我知道下面的重构,但实际的问题不能用这种方式重构。
func PrintAndStop(ctx context.Context, numberOfTimePrint int, msg string) {
completed := true
for i := 0; i < numberOfTimePrint; i++ {
select {
case <-time.After(1 * time.Second):
fmt.Println(msg)
case <-ctx.Done():
fmt.Println("closing call from the main function")
completed = false
break
}
}
if completed {
fmt.Println("function execution is completed")
}
}备注:我很高兴在Go中使用context库的一些扩展或一些全新的库来解决上述问题。
发布于 2020-07-20 11:47:50
--我想要控制主函数,以便随时停止
PrintAndStop的执行
然后,需要检查是否取消了该循环中的上下文。
go func() {
for i := 0; i < int(timeout/time.Second); i++ {
select {
case <-ctx.Done():
return
}
fmt.Println(msg)
time.Sleep(time.Second)
}
communicationChannel <- true
}()https://stackoverflow.com/questions/62994564
复制相似问题