登录
首页 >  Golang >  Go问答

停止执行一个不复杂的函数

来源:stackoverflow

时间:2024-03-08 23:24:25 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相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>