Home  >  Article  >  Backend Development  >  Golang Concurrent Programming Basics Tutorial: From Getting Started with Goroutines to Practical Applications

Golang Concurrent Programming Basics Tutorial: From Getting Started with Goroutines to Practical Applications

王林
王林Original
2023-07-18 20:34:561097browse

Golang Concurrent Programming Basics Tutorial: From Getting Started with Goroutines to Practical Applications

Introduction:
With the rapid development of the Internet, the demand for efficient concurrent processing is also increasing. As a fast and efficient programming language, Golang is popular for its powerful concurrency support. This article will introduce the basic knowledge of concurrent programming in Golang, from getting started with Goroutines to practical applications.

1. What is Goroutine?
Goroutine is a lightweight thread in Golang that can run concurrently with other Goroutines. The cost of creating and destroying Goroutines is very low, so thousands of Goroutines can be easily created to achieve high concurrency processing.

The following is a simple example showing how to create and run a Goroutine:

package main

import (
    "fmt"
    "time"
)

func foo() {
    for i := 0; i < 5; i++ {
        fmt.Println("Goroutine:", i)
        time.Sleep(time.Millisecond * 500)
    }
}

func main() {
    go foo() // 创建并运行一个Goroutine
    for i := 0; i < 5; i++ {
        fmt.Println("Main:", i)
        time.Sleep(time.Millisecond * 500)
    }
}

In the above example, we created a function named foo and In the main() function, a Goroutine is created through the go keyword to concurrently execute the foo() function. As you can see, the main thread and Goroutine run at the same time, outputting every 500 milliseconds.

2. Communication between Goroutines
Goroutines can communicate through channels. Channel is a type used for synchronizing and passing data. It can be thought of as a queue, and Goroutine can send and receive data through the channel.

The following is a simple example showing how to use channels for communication between Goroutines:

package main

import (
    "fmt"
)

func send(c chan<- int) {
    for i := 0; i < 5; i++ {
        c <- i // 将数据发送到channel中
    }
    close(c) // 关闭channel
}

func receive(c <-chan int) {
    for num := range c { // 从channel中读取数据,直到channel被关闭
        fmt.Println("Received:", num)
    }
}

func main() {
    c := make(chan int) // 创建一个channel

    go send(c)    // 创建并运行发送Goroutine
    receive(c)    // 接收Goroutine

    fmt.Println("Main exits")
}

In the above example, we created a send function and a receiveFunction. The send function sends integers from 0 to 4 to the receive function through the channel, and the receive function reads data from the channel and outputs it. In the main function, we create a channel and execute the send and receive functions concurrently through Goroutines. Data transmission and synchronization are performed through channels.

3. Goroutine synchronization and waiting
In actual development, we may need to wait for all Goroutines to complete before continuing to the next step. Golang provides the sync package to implement synchronization and waiting for Goroutines.

Here is a simple example showing how to use sync.WaitGroup to wait for Goroutines to complete:

package main

import (
    "fmt"
    "sync"
    "time"
)

func foo(wg *sync.WaitGroup) {
    defer wg.Done() // 触发WaitGroup计数器减1
    for i := 0; i < 5; i++ {
        fmt.Println("Goroutine:", i)
        time.Sleep(time.Millisecond * 500)
    }
}

func main() {
    var wg sync.WaitGroup

    wg.Add(1)      // 增加WaitGroup计数器
    go foo(&wg)    // 创建并运行一个Goroutine

    wg.Wait()      // 等待所有Goroutines完成

    fmt.Println("Main exits")
}

In the above example, we create a WaitGroup Instance, and add a counter in the main() function. In the foo() function, we use the defer statement to trigger the operation of decrementing the counter by 1. Wait for the completion of Goroutines through the Wait() method of WaitGroup. This ensures that all Goroutines are executed before continuing to execute subsequent code.

Conclusion:
Through the introduction of this article, we have learned the basics of concurrent programming in Golang. From the creation and running of Goroutines, to the use of channels for communication between Goroutines, to the use of sync.WaitGroup to achieve synchronization and waiting of Goroutines, we can better apply Golang's concurrent programming features to improve the program performance and efficiency.

Through learning to further master the concurrent programming of Golang, I believe it will be of great help in developing high-concurrency Internet applications. Let us continue to explore in practice and apply it to actual development to create a better application experience for users.

The above is the detailed content of Golang Concurrent Programming Basics Tutorial: From Getting Started with Goroutines to Practical Applications. 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