停止执行一个不复杂的函数
时间:2024-03-08
浏览:121
作者:佚名
怎么入门Golang编程?需要学习哪些知识点?这是新手们刚接触编程时常见的问题;下面golang学习网就来给大家整理分享一些知识点,希望能够给初学者一些帮助。本篇文章就来介绍《停止执行一个不复杂的函数》,涉及到,有需要的可以收藏一下
问题内容
据我了解,上下文库的主要目的是停止所有子进程的 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) 只是表示 main 函数在函数调用后并未结束。
我知道以下重构,但实际问题不能这样重构。
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")
}
}
注意:我很高兴使用 context 库的某些扩展或 go 中的一些全新库来解决上述问题。
解决方案
然后您需要检查该循环内的上下文是否被取消:
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
}()
终于介绍完啦!小伙伴们,这篇关于《停止执行一个不复杂的函数》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.29
热门专题
