【问题标题】:Cancelling user specific goroutines [closed]取消用户特定的 goroutines [关闭]
【发布时间】:2019-01-13 05:04:49
【问题描述】:

我有一个应用程序(网络应用程序)让用户使用 twitter oauth 登录并提供自动推文删除功能。在用户登录到网络应用程序后,我将为每个用户启动一个 goroutines(通过 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))
}

【问题讨论】:

  • 为了在中间停止 goroutines 使用 channel 发送一个信号来停止 goroutine。
  • 你有没有尝试过?如果可以,能否贴出相关代码?
  • 用代码编辑过的帖子

标签: go twitter concurrency goroutine


【解决方案1】:

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

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

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

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

【讨论】:

    【解决方案2】:

    我如何停止 [...] goroutine

    你使用例如启动 goroutine一个 done 通道,一旦 done 通道关闭,你就会停止你的 goroutine。

    考虑到 http 请求和 twitter API 限制,创建 go 例程以最大化应用程序性能的最佳实践是什么

    这个问题太宽泛了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-13
      • 2021-04-23
      • 1970-01-01
      • 2018-03-05
      • 2019-05-13
      • 1970-01-01
      相关资源
      最近更新 更多