登录
首页 >  Golang >  Go问答

终止特定用户的goroutine

来源:stackoverflow

时间:2024-03-08 14:21:24 184浏览 收藏

一分耕耘,一分收获!既然打开了这篇文章《终止特定用户的goroutine》,就坚持看下去吧!文中内容包含等等知识点...希望你能在阅读本文后,能真真实实学到知识或者帮你解决心中的疑惑,也欢迎大佬或者新人朋友们多留言评论,多给建议!谢谢!

问题内容

我有一个应用程序(网络应用程序),允许用户使用 twitter oauth 登录并提供自动推文删除功能。用户登录到 web 应用程序后,我将为每个用户启动一个 goroutine(通过 rest api),以删除用户推文列表。

假设有 100 个用户,每个用户有 500 条以上的推文:

  • 如何在删除过程中停止删除 go 例程。

    例如:用户 30 在启动删除过程 2 分钟后请求停止删除推文(这应该通过对我的应用程序的 api 调用来完成)。

  • 考虑到 http 请求和 twitter api 限制,创建 go 例程的最佳实践是什么,以便最大限度地提高应用程序的性能。我应该为每个用户创建 go 例程还是实施工作池?

信息:我正在使用 anaconda 作为 twitter 客户端后端

编辑:

我找到了一种使用带有上下文的地图来实现此目的的方法。这是供参考的代码。归功于 https://gist.github.com/montanaflynn/020e75c6605dbe2c726e410020a7a974

package main

import (
    "context"
    "fmt"
    "log"
    "net/http"
    "sync"
    "time"
)

// a concurrent safe map type by embedding sync.Mutex
type cancelMap struct {
    sync.Mutex
    internal map[string]context.CancelFunc
}

func newCancelMap() *cancelMap {
    return &cancelMap{
        internal: make(map[string]context.CancelFunc),
    }
}

func (c *cancelMap) Get(key string) (value context.CancelFunc, ok bool) {
    c.Lock()
    result, ok := c.internal[key]
    c.Unlock()
    return result, ok
}

func (c *cancelMap) Set(key string, value context.CancelFunc) {
    c.Lock()
    c.internal[key] = value
    c.Unlock()
}

func (c *cancelMap) Delete(key string) {
    c.Lock()
    delete(c.internal, key)
    c.Unlock()
}

// create global jobs map with cancel function
var jobs = newCancelMap()

// the pretend worker will be wrapped here
// https://siadat.github.io/post/context
func work(ctx context.Context, id string) {

    for {
        select {
        case <-ctx.Done():
            fmt.Printf("Cancelling job id %s\n", id)
            return
        case <-time.After(time.Second):
            fmt.Printf("Doing job id %s\n", id)
        }
    }
}

func startHandler(w http.ResponseWriter, r *http.Request) {

    // get job id and name from query parameters
    id := r.URL.Query().Get("id")

    // check if job already exists in jobs map
    if _, ok := jobs.Get(id); ok {
        fmt.Fprintf(w, "Already started job id: %s\n", id)
        return
    }

    // create new context with cancel for the job
    ctx, cancel := context.WithCancel(context.Background())

    // save it in the global map of jobs
    jobs.Set(id, cancel)

    // actually start running the job
    go work(ctx, id)

    // return 200 with message
    fmt.Fprintf(w, "Job id: %s has been started\n", id)
}

func stopHandler(w http.ResponseWriter, r *http.Request) {

    // get job id and name from query parameters
    id := r.URL.Query().Get("id")

    // check for cancel func from jobs map
    cancel, found := jobs.Get(id)
    if !found {
        fmt.Fprintf(w, "Job id: %s is not running\n", id)
        return
    }

    // cancel the jobs
    cancel()

    // delete job from jobs map
    jobs.Delete(id)

    // return 200 with message
    fmt.Fprintf(w, "Job id: %s has been canceled\n", id)
}

func main() {
    http.HandleFunc("/start", startHandler)
    http.HandleFunc("/stop", stopHandler)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

解决方案


你不能从外部停止一个goroutine,goroutine必须支持取消操作。详情参见:cancel a blocking operation in Go。支持取消的常用手段是channels和context包。

至于哪个更适合您,这个范围太宽泛了。这取决于很多事情,但作为示例/参考,标准库的 HTTP 服务器在其自己的 goroutine 中为每个传入的 HTTP 请求提供服务,并且具有不错的性能。

如果您的请求率很高,可能值得创建和使用 goroutine 池(或使用执行此操作的第 3 方库/路由器),但这实际上取决于您的实际代码,您应该测量/分析您的应用程序来决定是否需要或是否值得。

通常我们可以说,如果每个 Goroutine 所做的工作与创建/调度 Goroutine 所需的开销相比“很大”,那么通常只使用新的 Goroutine 会更干净。在 Goroutine 中访问第 3 方服务(例如 Twitter API)可能比启动 Goroutine 的工作量和延迟多出几个数量级,因此您应该可以为每个 Goroutine 启动一个 Goroutine(不会造成性能损失)。

你可以用例如:一个完成通道,一旦完成通道关闭,你就停止你的 goroutine。

这个问题太宽泛了。

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《终止特定用户的goroutine》文章吧,也可关注golang学习网公众号了解相关技术文章。

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