The context package is used to manage coroutine execution in Golang function concurrent programming. It provides the following functions: propagating cancellation signals and allowing coroutines to interrupt other coroutines before the task is completed. Set a deadline. If the coroutine is not completed within the deadline, it will be automatically canceled. Pass additional information, allowing key-value pairs to be passed between coroutines.
The role of context in Golang function concurrent programming
context
package is used for management in Golang A key tool for concurrent function execution. It provides the ability to pass request cancellation signals, deadlines, and other relevant information between coroutines.
Function
Allows the coroutine to transmit cancellation signals, thereby allowing the initiator A coroutine interrupts a running coroutine before the task is completed.
You can specify the deadline. If the coroutine is not completed before the deadline, it will be automatically canceled.
Can carry any type of key-value pairs, allowing additional information to be passed between coroutines.
Using
To create acontext object, you can use
context.Background() or
context.WithCancel().
// 创建一个新context,取消信号为默认 ctx := context.Background() // 创建一个带有取消信号的新context ctx, cancel := context.WithCancel()
Cancel the coroutine
To cancel the coroutine, just call thecancel() function. This will send a cancellation signal to all coroutines listening on this
context.
// 取消协程 cancel()
Listen to the cancellation signal
The coroutine can use thecontext.Done() channel to listen to the cancellation signal. When the channel is closed, it indicates that
context has been cancelled.
// 监听取消信号 select { case <-ctx.Done(): // 处理取消 }
Practical Case
Consider the following coroutine that times outHTTP requests:
func MakeRequest(ctx context.Context, url string) (*http.Response, error) { // 创建一个带有截止时间的context ctx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() // 发起HTTP请求 req, err := http.NewRequest(http.MethodGet, url, nil) if err != nil { return nil, err } req = req.WithContext(ctx) resp, err := http.DefaultClient.Do(req) if err != nil { return nil, err } return resp, nil }
to create a
context with a 10 second deadline.
, allowing the underlying network call to timeout and cancel the request.
Ensure that
context is canceled when the function exits, preventing any other coroutines from being blocked.
context, we can control the execution of coroutines and avoid resource leaks and unnecessary waiting.
The above is the detailed content of The role of context in concurrent programming of Golang functions. For more information, please follow other related articles on the PHP Chinese website!