Golang context 原理分析
    		       		warning:
    		            这篇文章距离上次修改已过433天,其中的内容可能已经有所变动。
    		        
        		                
                
package main
 
import (
    "context"
    "fmt"
    "time"
)
 
func main() {
    // 创建一个带有超时的context
    ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
    defer cancel() // 确保我们在完成操作后取消context
 
    select {
    case <-time.After(1 * time.Second):
        fmt.Println("操作超时")
    case <-ctx.Done():
        fmt.Println("Context 完成:", ctx.Err())
    }
}这段代码创建了一个带有500毫秒超时的context,并在1秒后检查context是否完成。如果context在指定的时间内完成,会打印一条消息表示完成,并且会输出context完成的错误信息。如果context超时,会输出超时的消息。这个例子展示了如何使用context包来管理goroutine的执行时间。
评论已关闭