search
HomeCommon ProblemHow to implement concurrency control in go language

How to implement concurrency control in go language

Jun 08, 2023 pm 02:20 PM
go concurrency control

Methods for implementing concurrency control in go language: 1. WaitGroup, the task processing of multiple goroutines has a dependency or splicing relationship; 2. Channel, you can actively cancel goroutines; transfer data in multiple groutines; instead of the work of WaitGroup, Meet the functions of Context; 3. Context, signal propagation between multi-level groutines, including metadata propagation, cancellation of signal propagation, timeout control, etc.

How to implement concurrency control in go language

#The operating environment of this article: Windows 10 system, go1.20 version, dell g3 computer.

In Golang, you can open a goroutine through the go keyword, so you can easily write concurrent code in Go. But how to effectively control these concurrently executing groutines?

When it comes to concurrency control, many people may first think of locks. Golang also provides lock-related mechanisms, including mutex lock sync.Mutex and read-write lock sync.RWMutex. In addition to locks, there are also atomic operations sync/atomic, etc. However, the focus of these mechanisms is the concurrent data safety of goroutines. What this article wants to discuss is the concurrency behavior control of goroutine.

In goroutine concurrent behavior control, there are three common methods, namely WaitGroup, channel and Context.

WaitGroup

WaitGroup is located under the sync package. Its usage is as follows.

func main() {
  var wg sync.WaitGroup

  wg.Add(2) //添加需要完成的工作量2

  go func() {
    wg.Done() //完成工作量1
    fmt.Println("goroutine 1 完成工作!")
  }()

  go func() {
    wg.Done() //完成工作量1
    fmt.Println("goroutine 2 完成工作!")
  }()

  wg.Wait() //等待工作量2均完成
  fmt.Println("所有的goroutine均已完成工作!")}输出:
//goroutine 2 完成工作!
//goroutine 1 完成工作!
//所有的goroutine均已完成工作!

WaitGroup This concurrency control method is especially suitable for: a task requires multiple goroutines to work together. Each goroutine can only do part of the task. The task is completed only when all goroutines are completed. Therefore, WaitGroup has the same meaning as its name, which is a way of waiting.

However, in actual business, there is such a scenario: when a certain requirement is met, a certain goroutine needs to be actively notified to end. For example, if we start a background monitoring goroutine, when monitoring is no longer needed, we should notify the monitoring goroutine to end, otherwise it will keep idling and cause leaks.

Channel

For the above scenario, WaitGroup can do nothing. The simplest method that can be thought of: define a global variable and notify it by modifying this variable elsewhere. The background goroutine will constantly check this variable. If it finds that the variable has changed, it will close it by itself. However, this method is somewhat cumbersome. clumsy. In this case, channel select can come in handy.

func main() {
  exit := make(chan bool)

  go func() {
    for {
      select {
      case <p>This combination of channel select is a more elegant way to notify the goroutine of the end. </p><p>However, this solution also has limitations. Just imagine, what if there are multiple goroutines that all need to be controlled to end? What if these goroutines spawn other goroutines? Of course we can define many channels to solve this problem, but the relationship chain of goroutines leads to the complexity of this scenario. </p><h2>
<a id="Context_79"></a>Context</h2><p>The above scenarios are common under the CS architecture model. In Go, a separate goroutine (A) is often opened for each client to handle its series of requests, and often a single A will also request other services (start another goroutine B), and B may also request another goroutine. C, C then sends the request to the server of Databse, for example. Imagine that when the client disconnects, A, B, and C associated with it need to exit immediately before the system can reclaim the resources occupied by A, B, and C. Exiting A is simple, but how to notify B and C to also exit? </p><p>At this time, Context appears. </p><pre class="brush:php;toolbar:false">func A(ctx context.Context, name string)  {
  go B(ctx ,name) //A调用了B  for {
    select {
    case <p> In the example, a connection request is simulated from the client, and Goroutine A is opened accordingly for processing. A also enables B processing. Both A and B use Context for tracking. When we use the cancel function to notify the cancellation , these two goroutines will be terminated. </p><p>This is the control capability of Context. It is like a controller. After pressing the switch, all sub-Contexts based on this Context or derived from it will receive notifications. At this time, cleanup operations can be performed. Finally, Release goroutine, which elegantly solves the problem of uncontrollable goroutine after startup. </p><p>The detailed usage of Context is beyond the scope of this article. There will be a follow-up article specifically explaining the Context package, so stay tuned. </p><h2>
<a id="_140"></a>Summary</h2><p>This article lists three concurrency behavior control modes in Golang. There is no good or bad distinction between modes, it just depends on using appropriate solutions for different scenarios. In actual projects, multiple methods are often used in combination. </p>
  • WaitGroup: There is a dependency or splicing relationship between the task processing of multiple goroutines.
  • Channel select: You can actively cancel goroutine; data transfer in multiple groutines; channel can replace the work of WaitGroup, but it will increase the complexity of the code logic; multiple channels can meet the functions of Context, and similarly, it will also make the code logic becomes complicated.
  • Context: Signal propagation between multi-level groutines (including metadata propagation, cancellation of signal propagation, timeout control, etc.).

In Golang, you can open a goroutine through the go keyword, so you can easily write concurrent code in Go. But how to effectively control these concurrently executing groutines?

When it comes to concurrency control, many people may first think of locks. Golang also provides lock-related mechanisms, including mutex lock sync.Mutex and read-write lock sync.RWMutex. In addition to locks, there are also atomic operations sync/atomic, etc. However, the focus of these mechanisms is the concurrent data safety of goroutines. What this article wants to discuss is the concurrency behavior control of goroutine.

In goroutine concurrent behavior control, there are three common methods, namely WaitGroup, channel and Context.

The above is the detailed content of How to implement concurrency control in go language. For more information, please follow other related articles on the PHP Chinese website!

Statement
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.