SoFunction
Updated on 2025-03-03

Golang, Introduction to Concurrent Programming, Goroutine, Introduction and Basic Usage Summary

1. What is Goroutine?

GoroutineIt is a lightweight thread in Golang that is used to implement concurrent operations. Compared with traditional threads, Goroutine has the advantage of lower resource consumption and higher efficiency. Each Goroutine is managed by Go's scheduler at runtime and they share memory space. This makes it possible to run thousands of Goroutines on a single system thread.

1. Features of Goroutine:

  • Lightweight: The memory overhead is very small, about 2KB.
  • Non-preemptive scheduling: Goroutine voluntarily gave up the CPU and completed task switching through collaboration.
  • Concurrency and parallelism:Goroutine provides a concurrency model, and multiple tasks can be performed simultaneously.
  • Blocking model simplifies development: Avoid complex callback functions and make the code structure more concise.

2. How to start Goroutine

To start Goroutine, we just need to add the function call before thegoKeywords. This operation executes the function asynchronously in a separate Goroutine and the main program does not wait for it to complete.

grammar:

go function name (parameter)

Example 1: Basic Goroutine usage

package main
import (
    "fmt"
    "time"
)
func printMessage() {
    ("Goroutine is running!")
}
func main() {
    go printMessage() // Start Goroutine    (1 * ) // Pause the main thread to ensure that the Goroutine is executed    ("Main function is done.")
}

Output:

Goroutine is running!  
Main function is done.

explain:

  • Lord Goroutine (i.e.mainFunction) immediately starts a sub-Goroutine to runprintMessagefunction.
  • If not, the main Goroutine may end when the child Goroutine has not been executed, resulting in no output.

3. The relationship between the main Goroutine and the child Goroutine

  • Lord GoroutinemainThe Goroutine where the function is located, the program starts running from here.
  • Sub Goroutine: Goroutine created by the main Goroutine or other Goroutine.

Key point: If the main Goroutine ends, all unfinished child Goroutines are also forced to terminate.

Example 2: End of the main thread causes the child Goroutine to terminate

package main
import (
    "fmt"
    "time"
)
func main() {
    go func() {
        (2 * )
        ("This message may never appear.")
    }()
    ("Main function is done.")
    // The main Goroutine ends immediately, the child Goroutine has no chance to complete}

Output:

Main function is done.

explain:

When the main Goroutine ends, all unfinished child Goroutines stop immediately, so the output of the child Goroutine is not seen.

4. Parameter transfer of Goroutine

In Golang, Goroutine supports passing parameters, but it should be noted thatPass by value, not by reference.

Example 3: Goroutine passes parameters

package main
import (
    "fmt"
)
func printNumber(num int) {
    ("Number:", num)
}
func main() {
    for i := 1; i <= 3; i++ {
        go printNumber(i) // Start Goroutine to pass parameters    }
    () // Wait for user input to prevent the program from ending early}

Output (possible):

Number: 1  
Number: 2  
Number: 3

5. Variable capture problem in anonymous functions

Goroutine is often used with anonymous functions, but be carefulVariable Capturequestion. When starting Goroutine in a loop, the anonymous function may capture not the value of the current iterative variable, but the variable after the loop ends.

Example 4: Error variable capture

package main
import (
    "fmt"
    "time"
)
func main() {
    for i := 1; i <= 3; i++ {
        go func() {
            (i) // What is captured may be i after the loop is over        }()
    }
    (1 * )
}

Output:

4  
4  
4

Modified code: Pass variables as parameters

go func(n int) {
    (n)
}(i)

6. Use WaitGroup to wait for Goroutine to complete

Not the best way to wait for Goroutine to finish. Go providesto manage synchronization of multiple Goroutines.

Example 5: Using WaitGroup

package main
import (
    "fmt"
    "sync"
)
func printMessage(msg string, wg *) {
    defer () // Call Done() when Goroutine is completed    (msg)
}
func main() {
    var wg 
    (3) // Wait for 3 Goroutines    go printMessage("Hello", &wg)
    go printMessage("from", &wg)
    go printMessage("Goroutine!", &wg)
    () // Wait for all Goroutines to complete    ("All Goroutines are done.")
}

Output:

Hello  
from  
Goroutine!  
All Goroutines are done.

explain:

  • (n)Indicates that you need to wait for n Goroutines to complete.
  • Called at the end of each Goroutine()
  • ()The main Goroutine will be blocked until all tasks are completed.

7. Typical application scenarios of Goroutine

  • I/O concurrency: Process a large number of network requests and reduce response time.
  • Backstage tasks: Execute timing tasks, logging, etc.
  • parallel computing: Distribute computing tasks to improve program performance.
  • Timer and delay operation: For example, perform an operation every once in a while.

8. Precautions and best practices

  • Avoid deadlocks: When Goroutines may have deadlocks when they are waiting for each other, you should be careful with sharing resources.
  • Use WaitGroup and Channel rationally: Ensure Goroutine synchronization and communication.
  • Avoid excessive startup Goroutine: Although Goroutine is lightweight, too many Goroutines will also occupy system resources.
  • Debugging Tools:usego tool traceandpprofPerform performance tuning and debugging.

9. Summary

Goroutine is Golang's powerful concurrency tool. Its efficient and easy-to-use features make it the first choice for developers to implement concurrent programs. In this blog, we introduce the basic usage, parameter passing and synchronization mechanism of Goroutine, and demonstrate common application scenarios and precautions.

This is the article about the introduction to Golang concurrent programming: Goroutine introduction and basic usage. For more information about goland goroutine usage, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!