最新公告
  • 欢迎您光临码农资源网,本站秉承服务宗旨 履行“站长”责任,销售只是起点 服务永无止境!加入我们
  • golang函数如何控制goroutine的执行?

    go 函数控制 goroutine 执行有以下方式:runtime.goexit():强制终止当前 goroutine。sync.waitgroup: 等待一组 goroutines 完成。select{}:允许 goroutine 等待多个事件之一并根据第一个触发的事件执行相应操作。context.context: 可以用来向 goroutine 传递截止日期或取消请求。

    golang函数如何控制goroutine的执行?

    Go 函数如何控制 Goroutine 的执行

    Go 编程语言支持并发,并使用 Goroutine(轻量级线程)实现并发。Goroutine 可以通过函数创建,并在创建后的任何时候启动。本文将介绍用于控制 Goroutine 执行的不同函数,并提供一些实战案例。

    控制 Goroutine 执行的函数

    • runtime.Goexit():强行终止当前 Goroutine。
    • sync.WaitGroup: 等待一组 Goroutines 完成。
    • select{}:允许 Goroutine 等待多个事件之一并根据第一个触发的事件执行相应操作。
    • context.Context: 可以用来向 Goroutine 传递截止日期或取消请求。

    实战案例

    1. 终止 Goroutine

    package main
    
    import (
        "fmt"
        "runtime"
        "time"
    )
    
    func main() {
        go func() {
            for {
                fmt.Println("Goroutine is running...")
                time.Sleep(1 * time.Second)
            }
        }()
    
        // 等待 10 秒后终止 Goroutine
        time.Sleep(10 * time.Second)
        runtime.Goexit()
    }

    2. 使用 sync.WaitGroup 等待 Goroutine

    package main
    
    import (
        "fmt"
        "sync"
        "time"
    )
    
    func main() {
        var wg sync.WaitGroup
    
        // 创建 5 个 Goroutine
        for i := 0; i < 5; i++ {
            wg.Add(1)
            go func(i int) {
                fmt.Printf("Goroutine %d is running...n", i)
                time.Sleep(1 * time.Second)
                wg.Done()
            }(i)
        }
    
        // 等待所有 Goroutine 完成
        wg.Wait()
    }

    3. 使用 select{} 响应事件

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
        fmt.Println("Waiting for events...")
    
        // 创建两个 channel
        ch1 := make(chan string)
        ch2 := make(chan string)
    
        // 创建两个 Goroutine 向 channel 发送数据
        go func() {
            time.Sleep(1 * time.Second)
            ch1 <- "Event from Channel 1"
        }()
        go func() {
            time.Sleep(2 * time.Second)
            ch2 <- "Event from Channel 2"
        }()
    
        for {
            select {
                case msg := <-ch1:
                    fmt.Println(msg)
                    return
                case msg := <-ch2:
                    fmt.Println(msg)
                    return
            }
        }
    }

    4. 使用 context.Context 取消 Goroutine

    package main
    
    import (
        "context"
        "fmt"
        "time"
    )
    
    func main() {
        // 创建一个 context
        ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
        defer cancel()
    
        // 创建一个 Goroutine
        go func() {
            for {
                select {
                    case <-ctx.Done():
                        fmt.Println("Goroutine cancelled")
                        return
                    default:
                        fmt.Println("Goroutine is running...")
                        time.Sleep(1 * time.Second)
                }
            }
        }()
    
        // 等待 15 秒后取消 Goroutine
        time.Sleep(15 * time.Second)
        cancel()
    }
    想要了解更多内容,请持续关注码农资源网,一起探索发现编程世界的无限可能!
    本站部分资源来源于网络,仅限用于学习和研究目的,请勿用于其他用途。
    如有侵权请发送邮件至1943759704@qq.com删除

    码农资源网 » golang函数如何控制goroutine的执行?
    • 18会员总数(位)
    • 16045资源总数(个)
    • 1160本周发布(个)
    • 297 今日发布(个)
    • 113稳定运行(天)

    提供最优质的资源集合

    立即查看 了解详情