Golang并发编程-context包详解
    		       		warning:
    		            这篇文章距离上次修改已过441天,其中的内容可能已经有所变动。
    		        
        		                
                
package main
 
import (
    "context"
    "fmt"
    "time"
)
 
func main() {
    // 创建一个带有超时的context
    ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
    defer cancel() // 确保在main函数结束前取消context
 
    select {
    case <-ctx.Done():
        fmt.Println("Context is done:", ctx.Err())
    case <-time.After(700 * time.Millisecond):
        fmt.Println("Timeout is up")
    }
}这段代码使用context包中的WithTimeout函数创建了一个带有超时的context。ctx.Done()是一个channel,可以用来检测context是否被取消,ctx.Err()返回取消的原因。程序会等待500毫秒,如果在这段时间内context没有被取消,则会输出"Context is done: <错误信息>";如果在500毫秒之前程序退出,会输出"Timeout is up"。这个例子展示了如何使用context包来处理并发操作的超时和取消。
评论已关闭