卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章52466本站已运行31128

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()
}
卓越飞翔博客
上一篇: C++并发编程:如何处理线程间通信?
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏