登录
首页 >  Golang >  Go问答

启动和关闭函数的步骤

来源:stackoverflow

时间:2024-03-26 18:18:32 139浏览 收藏

本文解释了在 Go 中使用 上下文(Context) 管理 Goroutine 的方法,使您可以通过 HTTP 调用启动和停止函数。通过使用 WithCancel 函数创建一个可取消的上下文,可以在合适的时间安全地停止 Goroutine。文章还提供了在 main 函数中使用这种方法的示例,并强调了在 HTTP 环境中实现此功能时需要考虑的并发安全问题。

问题内容

我有一个 go 函数 processing,它使用两个不同的 goroutine。 produce 会将一些数据推送到通道中,consume 将读取这些数据。这是一个例子:

type myobject struct{
    ...
}

func processing() {
    var wg sync.waitgroup
    datachannel := make(chan myobject, 5)

    wg.add(2)

    go produce(wg, datachannel)
    go consume(wg, datachannel)

    wg.wait()
}

func produce (wg *sync.waitgroup, datachannel chan myobject){
    for{
        // produce data in datachannel
    }
}

func consume (wg *sync.waitgroup, datachannel chan myobject){
    for{
        // consume data from datachannel
    }
}

我希望我的 processing 函数通过 http 调用启动和停止。所以我想做如下事情:

func main() {

    // echo instance
    e := echo.New()
    e.GET("/", startProcessing)
    e.Logger.Fatal(e.Start(":8099"))
}

func startProcessing(c echo.Context) error{

    command := c.QueryParam("command")

    if(command == "start"){
        processing()
    }else if(command == "stop"){
        if (/* ? processing is running ? */){
            /* ? stop processing process? */
        }
    }       
}

使用 go 执行此操作的正确方法是什么?


解决方案


这里如何使用上下文启动和停止函数,请尝试 this

package main

import (
    "context"
    "fmt"
    "sync"
    "time"
)

func main() {
    ctx, cancel := context.WithCancel(context.Background())
    var wg sync.WaitGroup
    dataChannel := make(chan MyObject, 5)
    wg.Add(2)
    go produce(ctx, &wg, dataChannel)
    go consume(&wg, dataChannel)

    time.Sleep(1 * time.Second)
    cancel() // cancel when we are finished consuming data

    wg.Wait()
}

func produce(ctx context.Context, wg *sync.WaitGroup, dataChannel chan MyObject) {
    defer wg.Done()
    i := 1
    for {
        select {
        case <-ctx.Done():
            close(dataChannel)
            return // returning not to leak the goroutine
        case dataChannel <- MyObject{i}:
            i++
            time.Sleep(250 * time.Millisecond)
        }
    }
}

func consume(wg *sync.WaitGroup, dataChannel chan MyObject) {
    defer wg.Done()
    for v := range dataChannel {
        fmt.Println(v)
    }
}

type MyObject struct {
    i int
}

对于http你需要自己做!
它需要有一些并发安全 id 或映射或其他东西来跟踪您调用了多少个函数,然后调用 cancel() 来停止它。

好了,本文到此结束,带大家了解了《启动和关闭函数的步骤》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

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