登录
首页 >  Golang >  Go问答

停止在goroutine中调用新函数

来源:stackoverflow

时间:2024-02-28 16:42:20 230浏览 收藏

小伙伴们对Golang编程感兴趣吗?是否正在学习相关知识点?如果是,那么本文《停止在goroutine中调用新函数》,就很适合你,本篇文章讲解的知识点主要包括。在之后的文章中也会多多分享相关知识点,希望对大家的知识积累有所帮助!

问题内容

我需要在每次函数调用时取消任何先前的 goroutine 。在 go 中将如何处理?我已经看到了使用的通道,但我无法完全理解这些示例以及 select 语句是否是必要的。

期望的结果是仅运行最后一个请求子任务。

package main

import (
    "fmt"
    "time"
)

func main() {
    for i := 0; i < 5; i++ {
        go handleRequest(i)
        time.Sleep(1 * time.Second) // Time between requests
    }
}

func handleRequest(incr int) {
    fmt.Println("New request registered: ", incr + 1)
    for i := 0; i <= 3; i++ {
        fmt.Println("Request: ", incr + 1, " | Sub-task: ", i + 1)
        time.Sleep(2 * time.Second) // Time processing
    }
    return
}

解决方案


goroutine 取消可以使用上下文来完成。如果需要取消前一个 goroutine,请使用上下文启动它,并在新的 goroutine 启动时取消它。您必须编写 goroutine 来定期检查上下文:

var ctx context.context
   var cancel context.cancelfunc
   for i := 0; i < 5; i++ {
        if cancel!=nil {
             // cancel previous goroutine
             cancel()
        }
        ctx,cancel=context.withcancel(context.background())
        // start goroutine with a new context
        go handlerequest(ctx,i)
        time.sleep(1 * time.second) // time between requests
    }  
    if cancel!=nil {
       cancel() 
    }

在你的 goroutine 中,你必须检查取消:

func handleRequest(ctx context.Context,incr int) {
    fmt.Println("New request registered: ", incr + 1)
    for i := 0; i <= 3; i++ {
        fmt.Println("Request: ", incr + 1, " | Sub-task: ", i + 1)
        time.Sleep(2 * time.Second) // Time processing
        select {
           case <-ctx.Done():
             // canceled
             return
           default:
             // not canceled
        }
    }
    return
}

以上就是《停止在goroutine中调用新函数》的详细内容,更多关于的资料请关注golang学习网公众号!

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