Values of the context.Context type carry security credentials, tracing information, deadlines, and cancellation signals across API and process boundaries. Go programs pass Contexts explicitly along the entire function call chain from incoming RPCs and HTTP requests to outgoing requests. A function that is never request-specific may use context.Background(), but err on the side of passing a Context even if you think you don't need to. The default case is to pass a Context; only use context.Background() directly if you have a good reason why the alternative is a mistake.

Context 提供线程安全 主要用来在 goroutine 之间传递上下文信息,包括:取消信号、超时时间、截止时间、k-v 等,成为了并发控制和超时控制的标准做法,与它协作的 API 都可以由外部控制执行“取消”操作,例如:取消一个 HTTP 请求的执行

A simple problem

func Perform() {
	for {
		SomeFunction()
		time.Sleep(time.Second)
	}
}

go Perform()

The goal is to cancel the Perform either explicitly or automatically when a deadline is exceeded. The Context package was initially designed to implement exactly what we need: request cancelation and deadline.

type Context interface {
	Done() <-chan struct {}
	Err() error
	Deadline() (deadline time.Time, ok bool)
	Value(key interface{}) interface{}
}

all the methods perform a query and get information

Context API is designed to satisfy the following requirements:

  1. Cancelation should be advisory

A caller is not aware of the internals of the function it is invoking. It should not interrupt or panic the callee. It is the responsibility of every function to return on its own. Instead of forcing a function to stop, the caller should inform it that its work is no longer needed.

  1. Cancelation should be transitive

the cancelation information should be broadcast from caller down to all of its child functions.

Create a context

创建根结点 context