【问题标题】:How to cancel goroutines after certain amount of time如何在一定时间后取消 goroutine
【发布时间】:2017-03-27 11:30:49
【问题描述】:

我正在制作一个负载测试工具,它在 goroutine 中进行多个 HTTP 调用,它可以工作,但现在我试图让它只运行指定的持续时间。

睡眠结束后如何取消 goroutine?

我目前正在尝试做的是制作一个在指定持续时间内执行time.Sleep() 的 goroutine,完成后它将向频道广播一条消息。

在我的无限循环中,我监听 switch 语句中的消息,当它出现时我返回。这就像我想要的那样工作。

问题是,go httpPost() 行中的 goroutine 将继续进行 HTTP 调用。我什至尝试将通道传递到该函数并在那里监听相同的CALL_TIME_RAN_OUT 消息,但是无论出于何种原因,当我这样做时,goroutines 只运行一次然后立即返回,而不是等待消息在Sleep结尾播出。

有谁知道我可以采取更好的方法吗?这似乎不起作用。

这是代码(删除了不相关的部分):

func attack(cfg AttackConfig) {
    // some code ...

    var ar attackResponse
    ch := make(chan uint8, 8)

    go func() {
        time.Sleep(cfg.Duration * time.Second)
        ch <- CALL_TIME_RAN_OUT
    }()

    for {
        if atomic.LoadInt32(&currConnections) < atomic.LoadInt32(&maxConnections) - 1 {
            go httpPost(cfg, &ar, ch)
        }

        switch <-ch {
        // some other cases ...
        case CALL_TIME_RAN_OUT:
            fmt.Printf("%d seconds have elapsed. Shutting down!", cfg.Duration)
            return
        }
    }
}

func httpPost(cfg AttackConfig, a *attackResponse, ch chan uint8) {
    // some code here to create HTTP client ...

    for {
        // some code to make HTTP call ...

        switch <-ch {
        case CALL_TIME_RAN_OUT:
            return
        }
    }
}

【问题讨论】:

  • 检查contexts。他们的目标之一是提供取消原语。
  • 啊,谢谢,我会调查的。
  • 你能在 for 循环中添加类似 for startTime.Sub(time.Now()).Seconds() &gt; 60 {} 的东西吗?

标签: go


【解决方案1】:

使用包golang.org/x/net/context。 Go 1.7 将golang.org/x/net/context 包作为context 移动到标准库中。 因此,如果您使用 1.7+ 版本,只需 import context

用法很简单:

package main

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

func test(ctx context.Context) {
    t := time.Now()

    select {
    case <-time.After(1 * time.Second):
        fmt.Println("overslept")
    case <-ctx.Done():
    }
    fmt.Println("used:", time.Since(t))
}

func main() {
    ctx, _ := context.WithTimeout(context.Background(), 50*time.Millisecond)
    test(ctx)
}

【讨论】:

    猜你喜欢
    • 2021-08-05
    • 1970-01-01
    • 2012-04-08
    • 1970-01-01
    • 1970-01-01
    • 2017-12-13
    • 2017-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多