【go 并发编程】go 语言并发执行5个不同的函数

您可以使用 Go 语言的 Goroutine 特性来并发执行多个不同的函数。Goroutine 是轻量级线程,可以让您在 Go 程序中并发地执行多个任务。

以下是一个示例程序,该程序启动了 5 个 Goroutine,并行执行 5 个不同的函数:

package main

import (
    "fmt"
    "sync"
)

func foo1(wg *sync.WaitGroup) {
    
    
    defer wg.Done()
    fmt.Println("This is function foo1.")
}

func foo2(wg *sync.WaitGroup) {
    
    
    defer wg.Done()
    fmt.Println("This is function foo2.")
}

func foo3(wg *sync.WaitGroup) {
    
    
    defer wg.Done()
    fmt.Println("This is function foo3.")
}

func foo4(wg *sync.WaitGroup) {
    
    
    defer wg.Done()
    fmt.Println("This is function foo4.")
}

func foo5(wg *sync.WaitGroup) {
    
    
    defer wg.Done()
    fmt.Println("This is function foo5.")
}

func main() {
    
    
    // 创建 WaitGroup 用于同步 Goroutine 的执行
    var wg sync.WaitGroup

    // 启动 5 个 Goroutine,每个 Goroutine 执行一个函数
    wg.Add(5)
    go foo1(&wg)
    go foo2(&wg)
    go foo3(&wg)
    go foo4(&wg)
    go foo5(&wg)

    // 等待所有 Goroutine 执行完毕
    wg.Wait()

    fmt.Println("All functions have finished executing.")
}

在上面的示例程序中,我们首先定义了 5 个函数:foo1、foo2、foo3、foo4 和 foo5。然后,我们创建了一个 WaitGroup 用于同步 Goroutine 的执行,并启动了 5 个 Goroutine,每个 Goroutine 执行一个函数。最后,我们等待所有 Goroutine 执行完毕,并打印一条结束消息。

需要注意的是,在使用 Goroutine 时,您需要确保在并发访问共享资源时进行适当的同步,以避免数据竞争和死锁等问题。在本例中,我们使用了 sync.WaitGroup 来同步 Goroutine 的执行。

运行结果:

This is function foo2.
This is function foo5.
This is function foo1.
This is function foo4.
This is function foo3.
All functions have finished executing.

猜你喜欢

转载自blog.csdn.net/u013421629/article/details/130154904