【问题标题】:context - WithDeadline() vs WithTimeout() [closed]上下文 - WithDeadline() 与 WithTimeout() [关闭]
【发布时间】:2021-01-27 07:22:34
【问题描述】:

以下代码:

// Sample program to show how to use the WithDeadline function
// of the Context package.
package main

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

type data struct {
    UserID string
}

func main() {

    // Set a duration.
    // duration := 150 * time.Millisecond
    duration := time.Now().Add(3 * time.Second)

    // Create a context that is both manually cancellable and will signal
    // a cancel at the specified duration.
    ctx, cancel := context.WithDeadline(context.Background(), duration)
    defer cancel()

    // Create a channel to received a signal that work is done.
    ch := make(chan data, 1)
    // Ask the goroutine to do some work for us.
    go func() {

        // Simulate work.
        time.Sleep(50 * time.Millisecond)

        // Report the work is done.
        ch <- data{"123"}
    }()

    // Wait for the work to finish. If it takes too long move on.
    select {
    case d := <-ch:
        fmt.Println("work complete", d)
    case <-ctx.Done():
        fmt.Println("work cancelled")
    }
}

正在使用WithDeadline 发送定时器的cancel()。这可以使用:

duration := 150 * time.Millisecond

// Create a context that is both manually cancellable and will signal
// a cancel at the specified duration.
ctx, cancel := context.WithTimeout(context.Background(), duration)

在内部,context.WithTimeout 调用context.WithDeadline 函数并通过将超时添加到当前时间来生成截止日期。

context.WithTimeout()context.WithDeadline() 有何不同

【问题讨论】:

  • "context.WithTimeout() 与 context.WithDeadline() 有何不同?" -- 你在之前的段落中回答了你自己的问题:“在内部,context.WithTimeout 调用 context.WithDeadline 函数并通过将超时添加到当前时间来生成截止日期。”如果你看了代码,你还想知道什么?

标签: go channel goroutine


【解决方案1】:

context.WithTimeout() 与 context.WithDeadline() 有何不同

第一个需要一段持续时间,然后从现在开始取消,第二个是调用取消的绝对时间,如文档中所述,值得像往常一样阅读。

【讨论】:

    【解决方案2】:

    WithTimeout是执行WithDeadline(parent, time.Now().Add(timeout))的便捷函数。

    应用程序指定截止日期的方式不同。否则它们是相同的。

    根据您手头的值调用适当的函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-22
      • 2012-01-04
      • 1970-01-01
      • 2015-04-24
      • 2013-07-23
      • 2020-07-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多