golang函数与goroutine的协同

2024年 4月 29日 26.2k 0

在 go 编程中,函数和 goroutine 协同实现并发。goroutine 在函数中创建,函数的局部变量在 goroutine 中可见。goroutine 可以在实战中用于并发处理任务,如并发文件上传,通过创建负责上传不同文件的 goroutine 提高效率。使用 goroutine 时需注意:创建 goroutine 需适量避免资源匮乏;goroutine 无返回值,获取结果需使用并发原语;goroutine 无法直接停止或取消。

golang函数与goroutine的协同

Go 函数与 Goroutine 的协同

在 Go 编程语言中,goroutine 是一种并发机制,可以创建轻量级线程来执行代码。函数和 goroutine 相互配合,可以实现高效并发的编程。

函数与 Goroutine 的联系

Goroutine 可以在函数内部创建,函数中的局部变量和常量在 goroutine 中可见。Goroutine 结束时,其局部变量和常量将被回收。

以下示例展示了如何在函数中创建 goroutine 并传递参数:

package main

import (
    "fmt"
    "time"
)

func printHello(name string) {
    fmt.Printf("Hello, %s!n", name)
}

func main() {
    go printHello("World")
    time.Sleep(1 * time.Second)
}

在上述示例中,main 函数创建一个 goroutine 并传入参数"World"。goroutine 执行 printHello 函数,打印出 "Hello, World!n"

实战案例:并发文件上传

考虑一个需要并发上传多个文件的用例:

package main

import (
    "context"
    "fmt"
    "io"
    "os"
    "path/filepath"
    "time"

    "cloud.google.com/go/storage"
)

func uploadFile(w io.Writer, bucketName, objectName string) error {
    ctx := context.Background()
    client, err := storage.NewClient(ctx)
    if err != nil {
        return fmt.Errorf("storage.NewClient: %v", err)
    }
    defer client.Close()

    f, err := os.Open(objectName)
    if err != nil {
        return fmt.Errorf("os.Open: %v", err)
    }
    defer f.Close()

    ctx, cancel := context.WithTimeout(ctx, time.Second*30)
    defer cancel()

    o := client.Bucket(bucketName).Object(objectName)
    wc := o.NewWriter(ctx)
    if _, err := io.Copy(wc, f); err != nil {
        return fmt.Errorf("io.Copy: %v", err)
    }
    if err := wc.Close(); err != nil {
        return fmt.Errorf("Writer.Close: %v", err)
    }
    fmt.Fprintf(w, "File %v uploaded to %v.n", objectName, bucketName)
    return nil
}

func main() {
    bucketName := "bucket-name"
    objectNames := []string{"file1.txt", "file2.txt", "file3.txt"}

    for _, objectName := range objectNames {
        go uploadFile(os.Stdout, bucketName, objectName)
    }
}

在这个案例中,main 函数创建一个 goroutine 列表,每个 goroutine 从操作系统中读取一个文件并将其上传到 Google Cloud Storage。这允许应用程序并发上传多个文件,从而显着提高性能。

注意事项

使用 goroutine 时需要注意以下事项:

  • Goroutine 是轻量级的,因此很容易创建大量 goroutine。确保不会创建过多的 goroutine 而导致程序资源匮乏。
  • Goroutine 退出时不带任何返回值。如果要获取 goroutine 的结果,请使用通道或其他并发性原语。
  • Goroutine 是匿名的,因此无法直接停止或取消单个 goroutine。

以上就是golang函数与goroutine的协同的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论