The role of context in concurrent programming of Golang functions

王林
Release: 2024-04-17 14:27:02
Original
676 people have browsed it

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 concurrent programming of Golang functions

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

  • ##Cancel signal propagation: contextAllows the coroutine to transmit cancellation signals, thereby allowing the initiator A coroutine interrupts a running coroutine before the task is completed.
  • Deadline time setting: contextYou can specify the deadline. If the coroutine is not completed before the deadline, it will be automatically canceled.
  • Value passing: contextCan carry any type of key-value pairs, allowing additional information to be passed between coroutines.

Using

To create a

context object, you can use context.Background() or context.WithCancel().

// 创建一个新context,取消信号为默认
ctx := context.Background()

// 创建一个带有取消信号的新context
ctx, cancel := context.WithCancel()
Copy after login

Cancel the coroutine

To cancel the coroutine, just call the

cancel() function. This will send a cancellation signal to all coroutines listening on this context.

// 取消协程
cancel()
Copy after login

Listen to the cancellation signal

The coroutine can use the

context.Done() channel to listen to the cancellation signal. When the channel is closed, it indicates that context has been cancelled.

// 监听取消信号
select {
case <-ctx.Done():
    // 处理取消
}
Copy after login

Practical Case

Consider the following coroutine that times out

HTTP 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
}
Copy after login

In this example:

    Use
  • context.WithTimeout() to create a context with a 10 second deadline.
  • The request is set to this
  • context, allowing the underlying network call to timeout and cancel the request.
  • defer cancel() Ensure that context is canceled when the function exits, preventing any other coroutines from being blocked.
By using

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template