Home  >  Article  >  Backend Development  >  Collaboration between golang function and goroutine

Collaboration between golang function and goroutine

PHPz
PHPzOriginal
2024-04-29 12:06:01350browse

In Go programming, functions and goroutines work together to achieve concurrency. A goroutine is created in a function, and the local variables of the function are visible in the goroutine. Goroutine can be used in actual combat for concurrent processing tasks, such as concurrent file uploads. Efficiency can be improved by creating goroutines responsible for uploading different files. When using goroutine, please note: Create goroutine in an appropriate amount to avoid resource shortage; goroutine has no return value, and you need to use concurrency primitives to obtain results; goroutine cannot be stopped or canceled directly.

Collaboration between golang function and goroutine

Cooperation between Go functions and Goroutine

In the Go programming language, goroutine is a concurrency mechanism that can create lightweight threads to execute code. Functions and goroutines work together to achieve efficient concurrent programming.

The connection between function and Goroutine

Goroutine can be created inside the function, and the local variables and constants in the function are visible in the goroutine. When a Goroutine ends, its local variables and constants will be recycled.

The following example shows how to create a goroutine and pass parameters in a function:

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)
}

In the above example, the main function creates a goroutine and passes in parameters "World". The goroutine executes the printHello function and prints out "Hello, World!\n".

Practical Case: Concurrent File Upload

Consider a use case that requires concurrent uploading of multiple files:

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)
    }
}

In this case, the main function is created A list of goroutines, each goroutine reads a file from the operating system and uploads it to Google Cloud Storage. This allows applications to upload multiple files concurrently, significantly improving performance.

Notes

You need to pay attention to the following when using goroutine:

  • Goroutine is lightweight, so it is easy to create a large number of goroutines. Make sure not to create too many goroutines and starve the program of resources.
  • Goroutine exits without any return value. If you want to get the results of a goroutine, use channels or other concurrency primitives.
  • Goroutines are anonymous, so individual goroutines cannot be stopped or canceled directly.

The above is the detailed content of Collaboration between golang function and goroutine. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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