Home > Backend Development > Golang > Golang multi-threaded programming skills and example analysis

Golang multi-threaded programming skills and example analysis

王林
Release: 2024-03-01 09:12:04
Original
1233 people have browsed it

Golang multi-threaded programming skills and example analysis

Golang (Go language) is an open source programming language developed by Google that has excellent performance and concise syntax in handling concurrent programming. This article will introduce the skills and example analysis of multi-threaded programming in Golang, and help readers better understand the concepts and applications of concurrent programming through specific code examples.

1. Goroutine (Coroutine)

Goroutine is a lightweight thread in Golang and is managed by the runtime scheduler of the Go language. By using goroutine, we can easily implement concurrent execution functions. The following is a simple goroutine example:

package main

import (
    "fmt"
    "time"
)

func hello() {
    fmt.Println("Hello goroutine!")
}

func main() {
    go hello()
    time.Sleep(1 * time.Second)
    fmt.Println("Main function")
}
Copy after login

In this example, we use go hello() in the main function to start a new goroutine, in Print "Hello goroutine" in this goroutine. Use time.Sleep to ensure that the main function waits for one second to ensure that the goroutine has enough time to execute. This approach enables simple concurrent execution.

2. Channel

In Golang, Channel is the main mechanism used for communication between goroutines. Channels can be buffered or unbuffered, ensuring the order and security of data transmission. The following is a simple example of using Channel for data transfer:

package main

import (
    "fmt"
)

func produce(c chan int) {
    for i := 0; i < 5; i++ {
        c <- i
    }
    close(c)
}

func consume(c chan int) {
    for num := range c {
        fmt.Println("Consumed", num)
    }
}

func main() {
    c := make(chan int)
    go produce(c)
    consume(c)
}
Copy after login

In this example, we define a producer function produce and a consumer function consume, the producer sends integers from 0 to 4 to the Channel, and the consumer receives and prints these integers. Use close(c) to close the Channel to avoid deadlock.

3. WaitGroup (Waiting Group)

WaitGroup is a tool in Golang used to wait for a group of goroutines to complete execution. Through WaitGroup, we can ensure that all goroutines have been executed before continuing to execute the main program. The following is an example of using WaitGroup:

package main

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

var wg sync.WaitGroup

func worker(id int) {
    defer wg.Done()
    fmt.Printf("Worker %d starting
", id)
    time.Sleep(time.Second)
    fmt.Printf("Worker %d done
", id)
}

func main() {
    for i := 1; i <= 5; i++ {
        wg.Add(1)
        go worker(i)
    }
    wg.Wait()
    fmt.Println("All workers have finished")
}
Copy after login

In this example, we define a waitGroup wg, start 5 goroutines in the main function, and pass wg.Add (1) and wg.Done() to count the execution of goroutine. Use wg.Wait() to let the main function wait for all goroutines to finish executing before continuing.

Conclusion

Through the above examples, we have demonstrated the basic skills and sample applications of multi-threaded programming in Golang. In actual development, rational use of goroutine, Channel and WaitGroup can effectively implement concurrent programming and improve program performance and efficiency. I hope this article can help readers better understand and use Golang for multi-threaded programming.

The above is the detailed content of Golang multi-threaded programming skills and example analysis. 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