Go 上下文-WithDeadline()与WithTimeout()的比较

Go 上下文-WithDeadline()与WithTimeout()的比较,go,channel,goroutine,Go,Channel,Goroutine,以下代码: // 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() { // S

以下代码:

// 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")
    }
}
在内部,context.WithTimeout调用context.WithDeadline函数,并通过向当前时间添加超时来生成截止日期


context.WithTimeout与context.WithDeadline有何不同WithTimeout是使用DeadLineParent time.Now.Addtimeout执行的方便函数

这些函数在应用程序指定截止日期的方式上有所不同。否则它们是一样的

调用适合现有值的函数


context.WithTimeout与context.WithDeadline有何不同


第一个需要一段时间才能从现在开始取消,第二个需要一段绝对时间才能调用cancel,如文档中所述,这一点值得像往常一样阅读。

context.WithTimeout与context.WithDeadline有何不同?-您在前面的段落中回答了自己的问题:在内部,context.WithTimeout调用context.WithDeadline函数,并通过将超时添加到当前时间来生成截止日期。如果你读了代码,你还想知道什么?
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)